Fixed some crashes in response strings source generator, reorganized more submodules into their folders

This commit is contained in:
Kwoth
2022-01-02 03:49:54 +01:00
parent 9c590668df
commit 4b6af0e4ef
191 changed files with 120 additions and 80 deletions

View File

@@ -0,0 +1,339 @@
#nullable disable
using NadekoBot.Modules.Xp.Services;
namespace NadekoBot.Modules.Xp;
public partial class Xp
{
[Group]
public partial class Club : NadekoSubmodule<ClubService>
{
private readonly XpService _xps;
public Club(XpService xps)
=> _xps = xps;
[Cmd]
public async partial Task ClubTransfer([Leftover] IUser newOwner)
{
var club = _service.TransferClub(ctx.User, newOwner);
if (club is not null)
await ReplyConfirmLocalizedAsync(strs.club_transfered(Format.Bold(club.Name),
Format.Bold(newOwner.ToString())));
else
await ReplyErrorLocalizedAsync(strs.club_transfer_failed);
}
[Cmd]
public async partial Task ClubAdmin([Leftover] IUser toAdmin)
{
bool admin;
try
{
admin = _service.ToggleAdmin(ctx.User, toAdmin);
}
catch (InvalidOperationException)
{
await ReplyErrorLocalizedAsync(strs.club_admin_error);
return;
}
if (admin)
await ReplyConfirmLocalizedAsync(strs.club_admin_add(Format.Bold(toAdmin.ToString())));
else
await ReplyConfirmLocalizedAsync(strs.club_admin_remove(Format.Bold(toAdmin.ToString())));
}
[Cmd]
public async partial Task ClubCreate([Leftover] string clubName)
{
if (string.IsNullOrWhiteSpace(clubName) || clubName.Length > 20)
{
await ReplyErrorLocalizedAsync(strs.club_name_too_long);
return;
}
if (!_service.CreateClub(ctx.User, clubName, out var club))
{
await ReplyErrorLocalizedAsync(strs.club_create_error);
return;
}
await ReplyConfirmLocalizedAsync(strs.club_created(Format.Bold(club.ToString())));
}
[Cmd]
public async partial Task ClubIcon([Leftover] string url = null)
{
if ((!Uri.IsWellFormedUriString(url, UriKind.Absolute) && url is not null)
|| !await _service.SetClubIcon(ctx.User.Id, url is null ? null : new Uri(url)))
{
await ReplyErrorLocalizedAsync(strs.club_icon_error);
return;
}
await ReplyConfirmLocalizedAsync(strs.club_icon_set);
}
[Cmd]
[Priority(1)]
public async partial Task ClubInformation(IUser user = null)
{
user ??= ctx.User;
var club = _service.GetClubByMember(user);
if (club is null)
{
await ErrorLocalizedAsync(strs.club_user_not_in_club(Format.Bold(user.ToString())));
return;
}
await ClubInformation(club.ToString());
}
[Cmd]
[Priority(0)]
public async partial Task ClubInformation([Leftover] string clubName = null)
{
if (string.IsNullOrWhiteSpace(clubName))
{
await ClubInformation(ctx.User);
return;
}
if (!_service.GetClubByName(clubName, out var club))
{
await ReplyErrorLocalizedAsync(strs.club_not_exists);
return;
}
var lvl = new LevelStats(club.Xp);
var users = club.Users.OrderByDescending(x =>
{
var l = new LevelStats(x.TotalXp).Level;
if (club.OwnerId == x.Id)
return int.MaxValue;
if (x.IsClubAdmin)
return (int.MaxValue / 2) + l;
return l;
});
await ctx.SendPaginatedConfirmAsync(0,
page =>
{
var embed = _eb.Create()
.WithOkColor()
.WithTitle($"{club}")
.WithDescription(GetText(strs.level_x(lvl.Level + $" ({club.Xp} xp)")))
.AddField(GetText(strs.desc),
string.IsNullOrWhiteSpace(club.Description) ? "-" : club.Description)
.AddField(GetText(strs.owner), club.Owner.ToString(), true)
.AddField(GetText(strs.level_req), club.MinimumLevelReq.ToString(), true)
.AddField(GetText(strs.members),
string.Join("\n",
users.Skip(page * 10)
.Take(10)
.Select(x =>
{
var l = new LevelStats(x.TotalXp);
var lvlStr = Format.Bold($" ⟪{l.Level}⟫");
if (club.OwnerId == x.Id)
return x + "🌟" + lvlStr;
if (x.IsClubAdmin)
return x + "⭐" + lvlStr;
return x + lvlStr;
})));
if (Uri.IsWellFormedUriString(club.ImageUrl, UriKind.Absolute))
return embed.WithThumbnailUrl(club.ImageUrl);
return embed;
},
club.Users.Count,
10);
}
[Cmd]
public partial Task ClubBans(int page = 1)
{
if (--page < 0)
return Task.CompletedTask;
var club = _service.GetClubWithBansAndApplications(ctx.User.Id);
if (club is null)
return ReplyErrorLocalizedAsync(strs.club_not_exists_owner);
var bans = club.Bans.Select(x => x.User).ToArray();
return ctx.SendPaginatedConfirmAsync(page,
_ =>
{
var toShow = string.Join("\n", bans.Skip(page * 10).Take(10).Select(x => x.ToString()));
return _eb.Create()
.WithTitle(GetText(strs.club_bans_for(club.ToString())))
.WithDescription(toShow)
.WithOkColor();
},
bans.Length,
10);
}
[Cmd]
public partial Task ClubApps(int page = 1)
{
if (--page < 0)
return Task.CompletedTask;
var club = _service.GetClubWithBansAndApplications(ctx.User.Id);
if (club is null)
return ReplyErrorLocalizedAsync(strs.club_not_exists_owner);
var apps = club.Applicants.Select(x => x.User).ToArray();
return ctx.SendPaginatedConfirmAsync(page,
_ =>
{
var toShow = string.Join("\n", apps.Skip(page * 10).Take(10).Select(x => x.ToString()));
return _eb.Create()
.WithTitle(GetText(strs.club_apps_for(club.ToString())))
.WithDescription(toShow)
.WithOkColor();
},
apps.Length,
10);
}
[Cmd]
public async partial Task ClubApply([Leftover] string clubName)
{
if (string.IsNullOrWhiteSpace(clubName))
return;
if (!_service.GetClubByName(clubName, out var club))
{
await ReplyErrorLocalizedAsync(strs.club_not_exists);
return;
}
if (_service.ApplyToClub(ctx.User, club))
await ReplyConfirmLocalizedAsync(strs.club_applied(Format.Bold(club.ToString())));
else
await ReplyErrorLocalizedAsync(strs.club_apply_error);
}
[Cmd]
[Priority(1)]
public partial Task ClubAccept(IUser user)
=> ClubAccept(user.ToString());
[Cmd]
[Priority(0)]
public async partial Task ClubAccept([Leftover] string userName)
{
if (_service.AcceptApplication(ctx.User.Id, userName, out var discordUser))
await ReplyConfirmLocalizedAsync(strs.club_accepted(Format.Bold(discordUser.ToString())));
else
await ReplyErrorLocalizedAsync(strs.club_accept_error);
}
[Cmd]
public async partial Task Clubleave()
{
if (_service.LeaveClub(ctx.User))
await ReplyConfirmLocalizedAsync(strs.club_left);
else
await ReplyErrorLocalizedAsync(strs.club_not_in_club);
}
[Cmd]
[Priority(1)]
public partial Task ClubKick([Leftover] IUser user)
=> ClubKick(user.ToString());
[Cmd]
[Priority(0)]
public partial Task ClubKick([Leftover] string userName)
{
if (_service.Kick(ctx.User.Id, userName, out var club))
return ReplyConfirmLocalizedAsync(strs.club_user_kick(Format.Bold(userName),
Format.Bold(club.ToString())));
return ReplyErrorLocalizedAsync(strs.club_user_kick_fail);
}
[Cmd]
[Priority(1)]
public partial Task ClubBan([Leftover] IUser user)
=> ClubBan(user.ToString());
[Cmd]
[Priority(0)]
public partial Task ClubBan([Leftover] string userName)
{
if (_service.Ban(ctx.User.Id, userName, out var club))
return ReplyConfirmLocalizedAsync(strs.club_user_banned(Format.Bold(userName),
Format.Bold(club.ToString())));
return ReplyErrorLocalizedAsync(strs.club_user_ban_fail);
}
[Cmd]
[Priority(1)]
public partial Task ClubUnBan([Leftover] IUser user)
=> ClubUnBan(user.ToString());
[Cmd]
[Priority(0)]
public partial Task ClubUnBan([Leftover] string userName)
{
if (_service.UnBan(ctx.User.Id, userName, out var club))
return ReplyConfirmLocalizedAsync(strs.club_user_unbanned(Format.Bold(userName),
Format.Bold(club.ToString())));
return ReplyErrorLocalizedAsync(strs.club_user_unban_fail);
}
[Cmd]
public async partial Task ClubLevelReq(int level)
{
if (_service.ChangeClubLevelReq(ctx.User.Id, level))
await ReplyConfirmLocalizedAsync(strs.club_level_req_changed(Format.Bold(level.ToString())));
else
await ReplyErrorLocalizedAsync(strs.club_level_req_change_error);
}
[Cmd]
public async partial Task ClubDescription([Leftover] string desc = null)
{
if (_service.ChangeClubDescription(ctx.User.Id, desc))
await ReplyConfirmLocalizedAsync(strs.club_desc_updated(Format.Bold(desc ?? "-")));
else
await ReplyErrorLocalizedAsync(strs.club_desc_update_failed);
}
[Cmd]
public async partial Task ClubDisband()
{
if (_service.Disband(ctx.User.Id, out var club))
await ReplyConfirmLocalizedAsync(strs.club_disbanded(Format.Bold(club.ToString())));
else
await ReplyErrorLocalizedAsync(strs.club_disband_error);
}
[Cmd]
public partial Task ClubLeaderboard(int page = 1)
{
if (--page < 0)
return Task.CompletedTask;
var clubs = _service.GetClubLeaderboardPage(page);
var embed = _eb.Create().WithTitle(GetText(strs.club_leaderboard(page + 1))).WithOkColor();
var i = page * 9;
foreach (var club in clubs) embed.AddField($"#{++i} " + club, club.Xp + " xp");
return ctx.Channel.EmbedAsync(embed);
}
}
}

View File

@@ -0,0 +1,317 @@
#nullable disable
using NadekoBot.Db;
using NadekoBot.Db.Models;
namespace NadekoBot.Modules.Xp.Services;
public class ClubService : INService
{
private readonly DbService _db;
private readonly IHttpClientFactory _httpFactory;
public ClubService(DbService db, IHttpClientFactory _httpFactory)
{
_db = db;
this._httpFactory = _httpFactory;
}
public bool CreateClub(IUser user, string clubName, out ClubInfo club)
{
//must be lvl 5 and must not be in a club already
club = null;
using var uow = _db.GetDbContext();
var du = uow.GetOrCreateUser(user);
uow.SaveChanges();
var xp = new LevelStats(du.TotalXp);
if (xp.Level >= 5 && du.Club is null)
{
du.IsClubAdmin = true;
du.Club = new() { Name = clubName, Discrim = uow.Clubs.GetNextDiscrim(clubName), Owner = du };
uow.Clubs.Add(du.Club);
uow.SaveChanges();
}
else
{
return false;
}
uow.Set<ClubApplicants>().RemoveRange(uow.Set<ClubApplicants>().AsQueryable().Where(x => x.UserId == du.Id));
club = du.Club;
uow.SaveChanges();
return true;
}
public ClubInfo TransferClub(IUser from, IUser newOwner)
{
ClubInfo club;
using var uow = _db.GetDbContext();
club = uow.Clubs.GetByOwner(from.Id);
var newOwnerUser = uow.GetOrCreateUser(newOwner);
if (club is null || club.Owner.UserId != from.Id || !club.Users.Contains(newOwnerUser))
return null;
club.Owner.IsClubAdmin = true; // old owner will stay as admin
newOwnerUser.IsClubAdmin = true;
club.Owner = newOwnerUser;
uow.SaveChanges();
return club;
}
public bool ToggleAdmin(IUser owner, IUser toAdmin)
{
bool newState;
using var uow = _db.GetDbContext();
var club = uow.Clubs.GetByOwner(owner.Id);
var adminUser = uow.GetOrCreateUser(toAdmin);
if (club is null || club.Owner.UserId != owner.Id || !club.Users.Contains(adminUser))
throw new InvalidOperationException();
if (club.OwnerId == adminUser.Id)
return true;
newState = adminUser.IsClubAdmin = !adminUser.IsClubAdmin;
uow.SaveChanges();
return newState;
}
public ClubInfo GetClubByMember(IUser user)
{
using var uow = _db.GetDbContext();
var member = uow.Clubs.GetByMember(user.Id);
return member;
}
public async Task<bool> SetClubIcon(ulong ownerUserId, Uri url)
{
if (url is not null)
{
using var http = _httpFactory.CreateClient();
using var temp = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
if (!temp.IsImage() || temp.GetImageSize() > 11)
return false;
}
await using var uow = _db.GetDbContext();
var club = uow.Clubs.GetByOwner(ownerUserId);
if (club is null)
return false;
club.ImageUrl = url.ToString();
uow.SaveChanges();
return true;
}
public bool GetClubByName(string clubName, out ClubInfo club)
{
club = null;
var arr = clubName.Split('#');
if (arr.Length < 2 || !int.TryParse(arr[arr.Length - 1], out var discrim))
return false;
//incase club has # in it
var name = string.Concat(arr.Except(new[] { arr[arr.Length - 1] }));
if (string.IsNullOrWhiteSpace(name))
return false;
using var uow = _db.GetDbContext();
club = uow.Clubs.GetByName(name, discrim);
if (club is null)
return false;
return true;
}
public bool ApplyToClub(IUser user, ClubInfo club)
{
using var uow = _db.GetDbContext();
var du = uow.GetOrCreateUser(user);
uow.SaveChanges();
if (du.Club is not null
|| new LevelStats(du.TotalXp).Level < club.MinimumLevelReq
|| club.Bans.Any(x => x.UserId == du.Id)
|| club.Applicants.Any(x => x.UserId == du.Id))
//user banned or a member of a club, or already applied,
// or doesn't min minumum level requirement, can't apply
return false;
var app = new ClubApplicants { ClubId = club.Id, UserId = du.Id };
uow.Set<ClubApplicants>().Add(app);
uow.SaveChanges();
return true;
}
public bool AcceptApplication(ulong clubOwnerUserId, string userName, out DiscordUser discordUser)
{
discordUser = null;
using var uow = _db.GetDbContext();
var club = uow.Clubs.GetByOwnerOrAdmin(clubOwnerUserId);
if (club is null)
return false;
var applicant =
club.Applicants.FirstOrDefault(x => x.User.ToString().ToUpperInvariant() == userName.ToUpperInvariant());
if (applicant is null)
return false;
applicant.User.Club = club;
applicant.User.IsClubAdmin = false;
club.Applicants.Remove(applicant);
//remove that user's all other applications
uow.Set<ClubApplicants>()
.RemoveRange(uow.Set<ClubApplicants>().AsQueryable().Where(x => x.UserId == applicant.User.Id));
discordUser = applicant.User;
uow.SaveChanges();
return true;
}
public ClubInfo GetClubWithBansAndApplications(ulong ownerUserId)
{
using var uow = _db.GetDbContext();
return uow.Clubs.GetByOwnerOrAdmin(ownerUserId);
}
public bool LeaveClub(IUser user)
{
using var uow = _db.GetDbContext();
var du = uow.GetOrCreateUser(user);
if (du.Club is null || du.Club.OwnerId == du.Id)
return false;
du.Club = null;
du.IsClubAdmin = false;
uow.SaveChanges();
return true;
}
public bool ChangeClubLevelReq(ulong userId, int level)
{
if (level < 5)
return false;
using var uow = _db.GetDbContext();
var club = uow.Clubs.GetByOwner(userId);
if (club is null)
return false;
club.MinimumLevelReq = level;
uow.SaveChanges();
return true;
}
public bool ChangeClubDescription(ulong userId, string desc)
{
using var uow = _db.GetDbContext();
var club = uow.Clubs.GetByOwner(userId);
if (club is null)
return false;
club.Description = desc?.TrimTo(150, true);
uow.SaveChanges();
return true;
}
public bool Disband(ulong userId, out ClubInfo club)
{
using var uow = _db.GetDbContext();
club = uow.Clubs.GetByOwner(userId);
if (club is null)
return false;
uow.Clubs.Remove(club);
uow.SaveChanges();
return true;
}
public bool Ban(ulong bannerId, string userName, out ClubInfo club)
{
using var uow = _db.GetDbContext();
club = uow.Clubs.GetByOwnerOrAdmin(bannerId);
if (club is null)
return false;
var usr = club.Users.FirstOrDefault(x => x.ToString().ToUpperInvariant() == userName.ToUpperInvariant())
?? club.Applicants
.FirstOrDefault(x => x.User.ToString().ToUpperInvariant() == userName.ToUpperInvariant())
?.User;
if (usr is null)
return false;
if (club.OwnerId == usr.Id
|| (usr.IsClubAdmin && club.Owner.UserId != bannerId)) // can't ban the owner kek, whew
return false;
club.Bans.Add(new() { Club = club, User = usr });
club.Users.Remove(usr);
var app = club.Applicants.FirstOrDefault(x => x.UserId == usr.Id);
if (app is not null)
club.Applicants.Remove(app);
uow.SaveChanges();
return true;
}
public bool UnBan(ulong ownerUserId, string userName, out ClubInfo club)
{
using var uow = _db.GetDbContext();
club = uow.Clubs.GetByOwnerOrAdmin(ownerUserId);
if (club is null)
return false;
var ban = club.Bans.FirstOrDefault(x => x.User.ToString().ToUpperInvariant() == userName.ToUpperInvariant());
if (ban is null)
return false;
club.Bans.Remove(ban);
uow.SaveChanges();
return true;
}
public bool Kick(ulong kickerId, string userName, out ClubInfo club)
{
using var uow = _db.GetDbContext();
club = uow.Clubs.GetByOwnerOrAdmin(kickerId);
if (club is null)
return false;
var usr = club.Users.FirstOrDefault(x => x.ToString().ToUpperInvariant() == userName.ToUpperInvariant());
if (usr is null)
return false;
if (club.OwnerId == usr.Id || (usr.IsClubAdmin && club.Owner.UserId != kickerId))
return false;
club.Users.Remove(usr);
var app = club.Applicants.FirstOrDefault(x => x.UserId == usr.Id);
if (app is not null)
club.Applicants.Remove(app);
uow.SaveChanges();
return true;
}
public List<ClubInfo> GetClubLeaderboardPage(int page)
{
if (page < 0)
throw new ArgumentOutOfRangeException(nameof(page));
using var uow = _db.GetDbContext();
return uow.Clubs.GetClubLeaderboardPage(page);
}
}