Skip to content

Commit

Permalink
Added transient service
Browse files Browse the repository at this point in the history
  • Loading branch information
ThomasAunvik committed May 10, 2020
1 parent f78ae9e commit b8df775
Show file tree
Hide file tree
Showing 18 changed files with 203 additions and 75 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class RequireValidAnimelistAttribute : PreconditionAttribute
{
public override async Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
{
DatabaseService db = services.GetRequiredService<DatabaseService>();
IDatabaseService db = services.GetRequiredService<IDatabaseService>();
DiscordUser user = await db.GetUserById(context.User.Id);
if (!user.HasValidAnimelist())
{
Expand Down
5 changes: 3 additions & 2 deletions AnimeListBot/Handler/CommandHandlingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public async Task MessageReceivedAsync(SocketMessage rawMessage)
if (guildChannel.Id == Config.cached.test_channel) return;
}

DatabaseService db = _services.GetRequiredService<DatabaseService>();
IDatabaseTrancientService db = _services.GetRequiredService<IDatabaseTrancientService>();

DiscordServer server = await db.GetServerById(guildChannel.GuildId);
server.UpdateGuildInfo(guildChannel.Guild);
Expand All @@ -98,6 +98,7 @@ public async Task MessageReceivedAsync(SocketMessage rawMessage)

// This value holds the offset where the prefix ends
var argPos = 0;

if (!(message.HasStringPrefix(server.Prefix, ref argPos) || message.HasMentionPrefix(Program._client.CurrentUser, ref argPos)))
return;

Expand All @@ -117,7 +118,7 @@ public async Task CommandExecutedAsync(Optional<CommandInfo> command, ICommandCo
if (!command.IsSpecified)
return;

DatabaseService db = _services.GetRequiredService<DatabaseService>();
IDatabaseService db = _services.GetRequiredService<IDatabaseService>();

DiscordUser user = await db.GetUserById(context.Message.Author.Id);
if (context.Message.Channel is IGuildChannel)
Expand Down
21 changes: 2 additions & 19 deletions AnimeListBot/Handler/Database/DatabaseConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public partial class DatabaseConnection : DbContext, IDisposable
public virtual DbSet<DiscordUser> DiscordUser { get; set; }
public virtual DbSet<Cluster> Cluster { get; set; }

private string GetConnectionString()
public static string GetConnectionString()
{
Config login = Config.GetConfig();
return string.Format("Server={0};Port={1};" +
Expand All @@ -44,26 +44,9 @@ private string GetConnectionString()
login.password, login.catalog);
}

public static async Task<DataSet> SendSql(string sql)
public DatabaseConnection(DbContextOptions<DatabaseConnection> options) : base(options)
{
Config login = Config.GetConfig();

string connstring = String.Format("Server={0};Port={1};" +
"User Id={2};Password={3};Database={4};",
login.ip, login.port, login.userid,
login.password, login.catalog);
NpgsqlConnection conn = new NpgsqlConnection(connstring);
await conn.OpenAsync();

NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
ds.Reset();

da.Fill(ds);

conn.Close();

return ds;
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
Expand Down
57 changes: 42 additions & 15 deletions AnimeListBot/Handler/Database/DatabaseService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,33 @@

namespace AnimeListBot.Handler.Database
{
public class DatabaseService : DatabaseConnection, IDisposable
public class DatabaseService : IDatabaseService
{
protected readonly DatabaseConnection dbConn;

public DatabaseService(DatabaseConnection db)
{
dbConn = db;
}

public List<DiscordServer> GetAllServers()
{
return DiscordServer.ToList();
return dbConn.DiscordServer.ToList();
}

public List<DiscordUser> GetAllUsers()
{
return DiscordUser.ToList();
return dbConn.DiscordUser.ToList();
}

public bool DoesServerIdExist(ulong id)
{
return DiscordServer.Find(id) == null;
return dbConn.DiscordServer.Find(id) == null;
}

public async Task<DiscordServer> GetServerById(ulong id)
{
DiscordServer server = await DiscordServer.FindAsync(id);
DiscordServer server = await dbConn.DiscordServer.FindAsync(id);
if (server == null)
{
server = new DiscordServer(Program._client.GetGuild(id));
Expand All @@ -36,21 +43,21 @@ public async Task<DiscordServer> GetServerById(ulong id)

public async Task<bool> CreateServer(DiscordServer server)
{
DiscordServer.Add(server);
await SaveChangesAsync();
dbConn.DiscordServer.Add(server);
await dbConn.SaveChangesAsync();
return true;
}

public async Task<bool> RemoveServer(DiscordServer server)
{
DiscordServer.Remove(await GetServerById(server.ServerId));
await SaveChangesAsync();
dbConn.DiscordServer.Remove(await GetServerById(server.ServerId));
await dbConn.SaveChangesAsync();
return true;
}

public async Task<DiscordUser> GetUserById(ulong id, bool forceUpdate = false)
{
DiscordUser user = DiscordUser.Find(id);
DiscordUser user = dbConn.DiscordUser.Find(id);
if (user == null)
{
await CreateUser(user = new DiscordUser(Program._client.GetUser(id)));
Expand All @@ -74,22 +81,42 @@ public async Task<DiscordUser> GetUserById(ulong id, bool forceUpdate = false)

public bool DoesUserIdExist(ulong id)
{
return DiscordUser.Find(id) != null;
return dbConn.DiscordUser.Find(id) != null;
}

public async Task<bool> CreateUser(DiscordUser user)
{
if (user == null || user.UserId == 0) return false;
DiscordUser.Add(user);
await SaveChangesAsync();
dbConn.DiscordUser.Add(user);
await dbConn.SaveChangesAsync();
return true;
}

public async Task<bool> RemoveUser(DiscordUser user)
{
DiscordUser.Remove(await GetUserById(user.UserId));
await SaveChangesAsync();
dbConn.DiscordUser.Remove(await GetUserById(user.UserId));
await dbConn.SaveChangesAsync();
return true;
}

public Cluster GetCluster(int id)
{
return dbConn.Cluster.Find(id);
}

public List<Cluster> GetAllClusters()
{
return dbConn.Cluster.ToList();
}

public async Task SaveChangesAsync()
{
await dbConn.SaveChangesAsync();
}

public void Dispose()
{
dbConn.Dispose();
}
}
}
26 changes: 26 additions & 0 deletions AnimeListBot/Handler/Database/DatabaseTrancientService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AnimeListBot.Handler.Database
{
public class DatabaseTrancientService : DatabaseService, IDatabaseTrancientService
{
public DatabaseTrancientService(DatabaseConnection db) : base (db)
{

}

public string GetServerPrefix(ulong guildId)
{
DiscordServer server = dbConn.DiscordServer.Find(guildId);
if(server != null)
{
return server.Prefix;
}
return "al!";
}
}
}
36 changes: 36 additions & 0 deletions AnimeListBot/Handler/Database/IDatabaseService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace AnimeListBot.Handler.Database
{
public interface IDatabaseService : IDisposable
{
public List<DiscordServer> GetAllServers();

public List<DiscordUser> GetAllUsers();

public bool DoesServerIdExist(ulong id);

public Task<DiscordServer> GetServerById(ulong id);

public Task<bool> CreateServer(DiscordServer server);

public Task<bool> RemoveServer(DiscordServer server);

public Task<DiscordUser> GetUserById(ulong id, bool forceUpdate = false);

public bool DoesUserIdExist(ulong id);

public Task<bool> CreateUser(DiscordUser user);

public Task<bool> RemoveUser(DiscordUser user);

public Cluster GetCluster(int id);

public List<Cluster> GetAllClusters();

public Task SaveChangesAsync();
}
}
11 changes: 11 additions & 0 deletions AnimeListBot/Handler/Database/IDatabaseTrancientService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace AnimeListBot.Handler.Database
{
public interface IDatabaseTrancientService : IDatabaseService
{
public string GetServerPrefix(ulong guildId);
}
}
13 changes: 9 additions & 4 deletions AnimeListBot/Modules/Administrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,12 @@ namespace AnimeListBot.Modules
[RequireOwner]
public class Administrator : ModuleBase<ShardedCommandContext>
{
public DatabaseService _db { get; set; }
private IDatabaseService _db;

public Administrator(IDatabaseService db)
{
_db = db;
}

[Command("stop")]
public async Task StopBot()
Expand Down Expand Up @@ -175,7 +180,7 @@ public async Task UpdateAllGuilds()
EmbedHandler embed = new EmbedHandler(Context.User, "Updating All Guilds");
await embed.SendMessage(Context.Channel);

List<DiscordServer> guilds = _db.DiscordServer.ToList();
List<DiscordServer> guilds = _db.GetAllServers();
for (int guildIndex = 0; guildIndex < guilds.Count; guildIndex++)
{
SocketGuild guild = Program._client.GetGuild(guilds[guildIndex].ServerId);
Expand All @@ -198,7 +203,7 @@ public async Task UpdateAllUsers()
EmbedHandler embed = new EmbedHandler(Context.User, "Updating All Users");
await embed.SendMessage(Context.Channel);

List<DiscordUser> users = _db.DiscordUser.ToList();
List<DiscordUser> users = _db.GetAllUsers();
for (int userIndex = 0; userIndex < users.Count; userIndex++)
{
DiscordUser user = users[userIndex];
Expand All @@ -215,7 +220,7 @@ public async Task TestCommand()
{
EmbedHandler embed = new EmbedHandler(Context.User, "Current Prefix");

DiscordServer server = _db.DiscordServer.Find(Context.Guild.Id);
DiscordServer server = await _db.GetServerById(Context.Guild.Id);
embed.Description = server.Prefix;

await _db.SaveChangesAsync();
Expand Down
7 changes: 6 additions & 1 deletion AnimeListBot/Modules/AutoAdder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@ namespace AnimeListBot.Modules
{
public class AutoAdder : ModuleBase<ShardedCommandContext>
{
public DatabaseService _db { get; set; }
private IDatabaseService _db;

public AutoAdder(IDatabaseService db)
{
_db = db;
}

[Command("autolist")]
[RequireUserPermission(GuildPermission.ManageRoles)]
Expand Down
7 changes: 6 additions & 1 deletion AnimeListBot/Modules/BotInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@ namespace AnimeListBot.Modules
{
public class BotInfo : ModuleBase<ShardedCommandContext>
{
public DatabaseService _db { get; set; }
private IDatabaseService _db;

public BotInfo(IDatabaseService db)
{
_db = db;
}

struct SavedStats
{
Expand Down
7 changes: 6 additions & 1 deletion AnimeListBot/Modules/Favorites.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,12 @@ namespace AnimeListBot.Modules
{
public class Favorites : ModuleBase<ShardedCommandContext>
{
public DatabaseService _db { get; set; }
private IDatabaseService _db;

public Favorites(IDatabaseService db)
{
_db = db;
}

[Command("favoriteanime")]
public async Task FavAnime(IUser user = null)
Expand Down
4 changes: 2 additions & 2 deletions AnimeListBot/Modules/HelpModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ public class HelpModule : ModuleBase<ShardedCommandContext>
{
private CommandService _service;
private readonly IServiceProvider _services;
private DatabaseService _db;
private IDatabaseService _db;

public HelpModule(CommandService service, IServiceProvider services, DatabaseService db)
public HelpModule(CommandService service, IServiceProvider services, IDatabaseService db)
{
_service = service;
_services = services;
Expand Down
9 changes: 7 additions & 2 deletions AnimeListBot/Modules/Profile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@ namespace AnimeListBot.Modules
{
public class Profile : ModuleBase<ShardedCommandContext>
{
public DatabaseService _db { get; set; }
private IDatabaseService _db;

public Profile(IDatabaseService db)
{
_db = db;
}

[Command("setup"), Summary(
"Registers your discord account with MAL. Possible options: [mal, anilist]\n" +
Expand Down Expand Up @@ -316,7 +321,7 @@ public async Task Leaderboard(int page = 1)
DiscordUser gUser = await _db.GetUserById(Context.User.Id);
DiscordServer server = await _db.GetServerById(Context.Guild.Id);

List<DiscordUser> users = _db.DiscordUser.ToList();
List<DiscordUser> users = _db.GetAllUsers();
List<DiscordUser> guildUsers = users.Where(y => y.Servers != null)
.Where(x => x.Servers.Find(y => y.ServerId == server.ServerId.ToString()) != null).ToList();

Expand Down
7 changes: 6 additions & 1 deletion AnimeListBot/Modules/Random.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,12 @@ namespace AnimeListBot.Modules
{
public class Random : ModuleBase<ShardedCommandContext>
{
public DatabaseService _db { get; set; }
private IDatabaseService _db;

public Random(IDatabaseService db)
{
_db = db;
}

class ListRequest
{
Expand Down
Loading

0 comments on commit b8df775

Please sign in to comment.