Updated editorconfig to (mostly?) require braces around if/else statements, and applied the new formatting rules

This commit is contained in:
Kwoth
2022-02-02 01:44:45 +01:00
parent b22cd5a81e
commit ffa2c3f119
202 changed files with 2108 additions and 920 deletions

View File

@@ -38,9 +38,9 @@ public partial class Searches
// await ctx.Channel.EmbedAsync(embed);
// }
[NadekoCommand, Aliases]
[Cmd]
[Priority(0)]
public async Task Mal([Leftover] string name)
public async partial Task Mal([Leftover] string name)
{
if (string.IsNullOrWhiteSpace(name))
return;

View File

@@ -24,7 +24,8 @@ public partial class Searches
.WithDescription(
GetText(strs.did_you_mean(Format.Bold($"{nearest.Name} ({nearest.Symbol})"))));
if (await PromptUserConfirmAsync(embed)) crypto = nearest;
if (await PromptUserConfirmAsync(embed))
crypto = nearest;
}
if (crypto is null)
@@ -43,7 +44,7 @@ public partial class Searches
var volume = usd.Volume24h.ToString("n0", Culture);
var marketCap = usd.MarketCap.ToString("n0", Culture);
await ctx.Channel.EmbedAsync(_eb.Create()
.WithOkColor()
.WithAuthor($"#{crypto.CmcRank}")

View File

@@ -67,7 +67,7 @@ public class CryptoService : INService
+ "&start=1"
+ "&limit=5000"
+ "&convert=USD");
return JsonSerializer.Serialize(strData);
}
catch (Exception ex)

View File

@@ -19,7 +19,8 @@ public partial class Searches
public partial Task YtUploadNotif(string url, [Leftover] ITextChannel channel = null)
{
var m = _ytChannelRegex.Match(url);
if (!m.Success) return ReplyErrorLocalizedAsync(strs.invalid_input);
if (!m.Success)
return ReplyErrorLocalizedAsync(strs.invalid_input);
var channelId = m.Groups["channelid"].Value;

View File

@@ -40,7 +40,7 @@ public class FeedsService : INService
_client = client;
_eb = eb;
_= Task.Run(TrackFeeds);
_ = Task.Run(TrackFeeds);
}
public async Task<EmbedBuilder> TrackFeeds()
@@ -74,7 +74,8 @@ public class FeedsService : INService
foreach (var (feedItem, itemUpdateDate) in items)
{
if (itemUpdateDate <= lastFeedUpdate) continue;
if (itemUpdateDate <= lastFeedUpdate)
continue;
var embed = _eb.Create().WithFooter(rssUrl);
@@ -159,26 +160,36 @@ public class FeedsService : INService
{
ArgumentNullException.ThrowIfNull(rssFeed, nameof(rssFeed));
var fs = new FeedSub { ChannelId = channelId, Url = rssFeed.Trim() };
var fs = new FeedSub
{
ChannelId = channelId,
Url = rssFeed.Trim()
};
using var uow = _db.GetDbContext();
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.FeedSubs).ThenInclude(x => x.GuildConfig));
if (gc.FeedSubs.Any(x => x.Url.ToLower() == fs.Url.ToLower()))
return false;
if (gc.FeedSubs.Count >= 10) return false;
if (gc.FeedSubs.Count >= 10)
return false;
gc.FeedSubs.Add(fs);
uow.SaveChanges();
//adding all, in case bot wasn't on this guild when it started
foreach (var feed in gc.FeedSubs)
{
_subs.AddOrUpdate(feed.Url.ToLower(),
new HashSet<FeedSub> { feed },
new HashSet<FeedSub>
{
feed
},
(_, old) =>
{
old.Add(feed);
return old;
});
}
return true;
}

View File

@@ -77,10 +77,12 @@ public partial class Searches
var sb = new StringBuilder();
foreach (var c in input)
{
if (_map.TryGetValue(c, out var tmp))
sb.Append(tmp);
else
sb.Append(c);
}
return sb.ToString();
}

View File

@@ -129,7 +129,8 @@ public partial class Searches
using var http = _httpFactory.CreateClient();
var m = 0;
if (!string.IsNullOrWhiteSpace(mode)) m = ResolveGameMode(mode);
if (!string.IsNullOrWhiteSpace(mode))
m = ResolveGameMode(mode);
var reqString = "https://osu.ppy.sh/api/get_user_best"
+ $"?k={_creds.OsuApiKey}"
@@ -159,7 +160,8 @@ public partial class Searches
var desc = $@"[/b/{item.BeatmapId}](https://osu.ppy.sh/b/{item.BeatmapId})
{pp + "pp",-7} | {acc + "%",-7}
";
if (mods != "+") desc += Format.Bold(mods);
if (mods != "+")
desc += Format.Bold(mods);
return (title, desc);
});
@@ -167,7 +169,8 @@ public partial class Searches
var eb = _eb.Create().WithOkColor().WithTitle($"Top 5 plays for {user}");
var mapData = await mapTasks.WhenAll();
foreach (var (title, desc) in mapData.Where(x => x != default)) eb.AddField(title, desc);
foreach (var (title, desc) in mapData.Where(x => x != default))
eb.AddField(title, desc);
await ctx.Channel.EmbedAsync(eb);
}

View File

@@ -142,7 +142,8 @@ public partial class Searches
return;
}
if (!string.IsNullOrWhiteSpace(league)) characters.RemoveAll(c => c.League != league);
if (!string.IsNullOrWhiteSpace(league))
characters.RemoveAll(c => c.League != league);
await ctx.SendPaginatedConfirmAsync(page,
curPage =>
@@ -155,7 +156,8 @@ public partial class Searches
var tempList = characters.Skip(curPage * 9).Take(9).ToList();
if (characters.Count == 0) return embed.WithDescription("This account has no characters.");
if (characters.Count == 0)
return embed.WithDescription("This account has no characters.");
var sb = new StringBuilder();
sb.AppendLine($"```{"#",-5}{"Character Name",-23}{"League",-10}{"Class",-13}{"Level",-3}");
@@ -218,7 +220,10 @@ public partial class Searches
}
[Cmd]
public async partial Task PathOfExileCurrency(string leagueName, string currencyName, string convertName = "Chaos Orb")
public async partial Task PathOfExileCurrency(
string leagueName,
string currencyName,
string convertName = "Chaos Orb")
{
if (string.IsNullOrWhiteSpace(leagueName))
{
@@ -293,7 +298,8 @@ public partial class Searches
private string ShortCurrencyName(string str)
{
if (currencyDictionary.ContainsValue(str)) return str;
if (currencyDictionary.ContainsValue(str))
return str;
var currency = currencyDictionary[str];

View File

@@ -28,6 +28,7 @@ public partial class Searches
return;
foreach (var kvp in Pokemons)
{
if (kvp.Key.ToUpperInvariant() == pokemon.ToUpperInvariant())
{
var p = kvp.Value;
@@ -46,6 +47,7 @@ public partial class Searches
true));
return;
}
}
await ReplyErrorLocalizedAsync(strs.pokemon_none);
}
@@ -57,6 +59,7 @@ public partial class Searches
if (string.IsNullOrWhiteSpace(ability))
return;
foreach (var kvp in PokemonAbilities)
{
if (kvp.Key.ToUpperInvariant() == ability)
{
await ctx.Channel.EmbedAsync(_eb.Create()
@@ -70,6 +73,7 @@ public partial class Searches
true));
return;
}
}
await ReplyErrorLocalizedAsync(strs.pokemon_ability_none);
}

View File

@@ -218,6 +218,7 @@ public partial class Searches : NadekoModule<SearchesService>
var oterms = query?.Trim();
if (!await ValidateQuery(query))
return;
query = WebUtility.UrlEncode(oterms)?.Replace(' ', '+');
try
{
@@ -287,7 +288,10 @@ public partial class Searches : NadekoModule<SearchesService>
{
using var http = _httpFactory.CreateClient();
using var req = new HttpRequestMessage(HttpMethod.Post, "https://goolnk.com/api/v1/shorten");
var formData = new MultipartFormDataContent { { new StringContent(query), "url" } };
var formData = new MultipartFormDataContent
{
{ new StringContent(query), "url" }
};
req.Content = formData;
using var res = await http.SendAsync(req);
@@ -486,7 +490,7 @@ public partial class Searches : NadekoModule<SearchesService>
{
e.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(12);
return http.GetStringAsync("https://api.pearson.com/v2/dictionaries/entries?headword="
+ WebUtility.UrlEncode(word));
+ WebUtility.UrlEncode(word));
});
var data = JsonConvert.DeserializeObject<DefineModel>(res);
@@ -572,6 +576,7 @@ public partial class Searches : NadekoModule<SearchesService>
if (string.IsNullOrWhiteSpace(imageLink))
return;
await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={imageLink}");
}
@@ -622,12 +627,6 @@ public partial class Searches : NadekoModule<SearchesService>
var avatarUrl = usr.RealAvatarUrl(2048);
if (avatarUrl is null)
{
await ReplyErrorLocalizedAsync(strs.avatar_none(usr.ToString()));
return;
}
await ctx.Channel.EmbedAsync(
_eb.Create()
.WithOkColor()
@@ -737,7 +736,8 @@ public partial class Searches : NadekoModule<SearchesService>
private async Task<bool> ValidateQuery(string query)
{
if (!string.IsNullOrWhiteSpace(query)) return true;
if (!string.IsNullOrWhiteSpace(query))
return true;
await ErrorLocalizedAsync(strs.specify_search_params);
return false;

View File

@@ -128,7 +128,8 @@ public class SearchesService : INService
{
TextOptions = new TextOptions
{
HorizontalAlignment = HorizontalAlignment.Center, WrapTextWidth = 190
HorizontalAlignment = HorizontalAlignment.Center,
WrapTextWidth = 190
}.WithFallbackFonts(_fonts.FallBackFonts)
},
text,
@@ -189,7 +190,8 @@ public class SearchesService : INService
{
query = query.Trim();
if (string.IsNullOrEmpty(query)) return (default, TimeErrors.InvalidInput);
if (string.IsNullOrEmpty(query))
return (default, TimeErrors.InvalidInput);
if (string.IsNullOrWhiteSpace(_creds.LocationIqApiKey) || string.IsNullOrWhiteSpace(_creds.TimezoneDbApiKey))
return (default, TimeErrors.ApiKeyMissing);
@@ -303,7 +305,12 @@ public class SearchesService : INService
{
using var http = _httpFactory.CreateClient();
var res = await http.GetStringAsync("https://official-joke-api.appspot.com/random_joke");
var resObj = JsonConvert.DeserializeAnonymousType(res, new { setup = "", punchline = "" });
var resObj = JsonConvert.DeserializeAnonymousType(res,
new
{
setup = "",
punchline = ""
});
return (resObj.setup, resObj.punchline);
}
@@ -395,7 +402,8 @@ public class SearchesService : INService
?? objs.FirstOrDefault(x => !string.IsNullOrEmpty(x.PlayerClass)) ?? objs.FirstOrDefault();
if (data is null)
return null;
if (!string.IsNullOrWhiteSpace(data.Img)) data.Img = await _google.ShortenUrl(data.Img);
if (!string.IsNullOrWhiteSpace(data.Img))
data.Img = await _google.ShortenUrl(data.Img);
if (!string.IsNullOrWhiteSpace(data.Text))
{
var converter = new Converter();
@@ -456,7 +464,14 @@ public class SearchesService : INService
// https://api.steampowered.com/ISteamApps/GetAppList/v2/
var gamesStr = await http.GetStringAsync("https://api.steampowered.com/ISteamApps/GetAppList/v2/");
var apps = JsonConvert
.DeserializeAnonymousType(gamesStr, new { applist = new { apps = new List<SteamGameId>() } })
.DeserializeAnonymousType(gamesStr,
new
{
applist = new
{
apps = new List<SteamGameId>()
}
})
.applist.apps;
return apps.OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase)

View File

@@ -67,7 +67,8 @@ public partial class Searches
[RequireContext(ContextType.Guild)]
public async partial Task StreamList(int page = 1)
{
if (page-- < 1) return;
if (page-- < 1)
return;
var streams = new List<FollowedStream>();
await using (var uow = _db.GetDbContext())

View File

@@ -74,7 +74,11 @@ public sealed class StreamNotificationService : INService
var followedStreams = guildConfigs.SelectMany(x => x.FollowedStreams).ToList();
_shardTrackedStreams = followedStreams.GroupBy(x => new { x.Type, Name = x.Username.ToLower() })
_shardTrackedStreams = followedStreams.GroupBy(x => new
{
x.Type,
Name = x.Username.ToLower()
})
.ToList()
.ToDictionary(
x => new StreamDataKey(x.Key.Type, x.Key.Name.ToLower()),
@@ -87,9 +91,14 @@ public sealed class StreamNotificationService : INService
{
var allFollowedStreams = uow.Set<FollowedStream>().AsQueryable().ToList();
foreach (var fs in allFollowedStreams) _streamTracker.CacheAddData(fs.CreateKey(), null, false);
foreach (var fs in allFollowedStreams)
_streamTracker.CacheAddData(fs.CreateKey(), null, false);
_trackCounter = allFollowedStreams.GroupBy(x => new { x.Type, Name = x.Username.ToLower() })
_trackCounter = allFollowedStreams.GroupBy(x => new
{
x.Type,
Name = x.Username.ToLower()
})
.ToDictionary(x => new StreamDataKey(x.Key.Type, x.Key.Name),
x => x.Select(fs => fs.GuildId).ToHashSet());
}
@@ -171,7 +180,10 @@ public sealed class StreamNotificationService : INService
if (_trackCounter.ContainsKey(key))
_trackCounter[key].Add(info.GuildId);
else
_trackCounter[key] = new() { info.GuildId };
_trackCounter[key] = new()
{
info.GuildId
};
}
return default;
@@ -351,10 +363,20 @@ public sealed class StreamNotificationService : INService
}
private void PublishFollowStream(FollowedStream fs)
=> _pubSub.Pub(_streamFollowKey, new() { Key = fs.CreateKey(), GuildId = fs.GuildId });
=> _pubSub.Pub(_streamFollowKey,
new()
{
Key = fs.CreateKey(),
GuildId = fs.GuildId
});
private Task PublishUnfollowStream(FollowedStream fs)
=> _pubSub.Pub(_streamUnfollowKey, new() { Key = fs.CreateKey(), GuildId = fs.GuildId });
=> _pubSub.Pub(_streamUnfollowKey,
new()
{
Key = fs.CreateKey(),
GuildId = fs.GuildId
});
public async Task<StreamData> FollowStream(ulong guildId, ulong channelId, string url)
{
@@ -370,7 +392,13 @@ public sealed class StreamNotificationService : INService
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.FollowedStreams));
// add it to the database
fs = new() { Type = data.StreamType, Username = data.UniqueName, ChannelId = channelId, GuildId = guildId };
fs = new()
{
Type = data.StreamType,
Username = data.UniqueName,
ChannelId = channelId,
GuildId = guildId
};
if (gc.FollowedStreams.Count >= 10)
return null;
@@ -454,7 +482,10 @@ public sealed class StreamNotificationService : INService
return map[guildId] = new();
}
_shardTrackedStreams[key] = new() { { guildId, new() } };
_shardTrackedStreams[key] = new()
{
{ guildId, new() }
};
return _shardTrackedStreams[key][guildId];
}

View File

@@ -110,7 +110,12 @@ public sealed class TranslateService : ITranslateService, ILateExecutor, IReadyE
if (old is null)
{
ctx.AutoTranslateChannels.Add(new() { GuildId = guildId, ChannelId = channelId, AutoDelete = autoDelete });
ctx.AutoTranslateChannels.Add(new()
{
GuildId = guildId,
ChannelId = channelId,
AutoDelete = autoDelete
});
await ctx.SaveChangesAsync();
@@ -169,7 +174,12 @@ public sealed class TranslateService : ITranslateService, ILateExecutor, IReadyE
if (user is null)
{
ch.Users.Add(user = new() { Source = from, Target = to, UserId = userId });
ch.Users.Add(user = new()
{
Source = from,
Target = to,
UserId = userId
});
await ctx.SaveChangesAsync();

View File

@@ -31,7 +31,8 @@ public class NotifChecker
{ FollowedStream.FType.Trovo, new TrovoProvider(httpClientFactory, credsProvider) }
};
_offlineBuffer = new();
if (isMaster) CacheClearAllData();
if (isMaster)
CacheClearAllData();
}
// gets all streams which have been failing for more than the provided timespan
@@ -45,12 +46,8 @@ public class NotifChecker
.ToList();
if (remove)
{
foreach (var toBeRemoved in toReturn)
{
_streamProviders[toBeRemoved.Type].ClearErrorsFor(toBeRemoved.Name);
}
}
return toReturn;
}
@@ -137,9 +134,11 @@ public class NotifChecker
Task.Delay(30_000)
};
if (newlyOnline.Count > 0) tasks.Add(OnStreamsOnline(newlyOnline));
if (newlyOnline.Count > 0)
tasks.Add(OnStreamsOnline(newlyOnline));
if (newlyOffline.Count > 0) tasks.Add(OnStreamsOffline(newlyOffline));
if (newlyOffline.Count > 0)
tasks.Add(OnStreamsOffline(newlyOffline));
await Task.WhenAll(tasks);
}
@@ -174,7 +173,8 @@ public class NotifChecker
public Dictionary<StreamDataKey, StreamData?> CacheGetAllData()
{
var db = _multi.GetDatabase();
if (!db.KeyExists(_key)) return new();
if (!db.KeyExists(_key))
return new();
return db.HashGetAll(_key)
.ToDictionary(entry => JsonConvert.DeserializeObject<StreamDataKey>(entry.Name),

View File

@@ -41,7 +41,10 @@ public class PicartoProvider : Provider
public override async Task<StreamData?> GetStreamDataAsync(string id)
{
var data = await GetStreamDataAsync(new List<string> { id });
var data = await GetStreamDataAsync(new List<string>
{
id
});
return data.FirstOrDefault();
}
@@ -54,6 +57,7 @@ public class PicartoProvider : Provider
using var http = _httpClientFactory.CreateClient();
var toReturn = new List<StreamData>();
foreach (var login in logins)
{
try
{
http.DefaultRequestHeaders.Accept.Add(new("application/json"));
@@ -77,6 +81,7 @@ public class PicartoProvider : Provider
ex.Message);
_failingStreams.TryAdd(login, DateTime.UtcNow);
}
}
return toReturn;
}

View File

@@ -11,8 +11,7 @@ public class TrovoProvider : Provider
public override FollowedStream.FType Platform
=> FollowedStream.FType.Trovo;
private readonly Regex _urlRegex
= new Regex(@"trovo.live\/(?<channel>[\w\d\-_]+)/?", RegexOptions.Compiled);
private readonly Regex _urlRegex = new(@"trovo.live\/(?<channel>[\w\d\-_]+)/?", RegexOptions.Compiled);
private readonly IBotCredsProvider _creds;
@@ -40,12 +39,12 @@ public class TrovoProvider : Provider
if (string.IsNullOrWhiteSpace(trovoClientId))
trovoClientId = "waiting for key";
http.DefaultRequestHeaders.Clear();
http.DefaultRequestHeaders.Add("Accept", "application/json");
http.DefaultRequestHeaders.Add("Client-ID", trovoClientId);
// trovo ratelimit is very generous (1200 per minute)
// so there is no need for ratelimit checks atm
try
@@ -60,7 +59,7 @@ public class TrovoProvider : Provider
res.EnsureSuccessStatusCode();
var data = await res.Content.ReadFromJsonAsync<TrovoGetUsersResponse>();
if (data is null)
{
Log.Warning("An empty response received while retrieving stream data for trovo.live/{TrovoId}", id);
@@ -79,7 +78,7 @@ public class TrovoProvider : Provider
StreamType = FollowedStream.FType.Picarto,
StreamUrl = data.ChannelUrl,
UniqueName = data.Username,
Preview = data.Thumbnail,
Preview = data.Thumbnail
};
}
catch (Exception ex)

View File

@@ -66,6 +66,7 @@ public class TwitchProvider : Provider
var toReturn = new List<StreamData>();
foreach (var login in logins)
{
try
{
// get id based on the username
@@ -117,6 +118,7 @@ public class TwitchProvider : Provider
ex.Message);
_failingStreams.TryAdd(login, DateTime.UtcNow);
}
}
return toReturn;
}