- Updated editorconfig rules to hopefully look a bit nicer.

- Removed configureawait(false) from everywhere as it doesnt' do anything in a console app and just makes the code look ugly
- Started using .WhenAll extension instead of Task.WhenAll to make it look nicer when chaining methods
This commit is contained in:
Kwoth
2021-12-28 21:14:26 +01:00
parent d093f7eed7
commit 723447c7d4
171 changed files with 1523 additions and 1594 deletions

View File

@@ -113,9 +113,9 @@ public class CommandHandler : INService
try
{
IUserMessage msg = await channel.SendMessageAsync(commandText).ConfigureAwait(false);
msg = (IUserMessage)await channel.GetMessageAsync(msg.Id).ConfigureAwait(false);
await TryRunCommand(guild, channel, msg).ConfigureAwait(false);
IUserMessage msg = await channel.SendMessageAsync(commandText);
msg = (IUserMessage)await channel.GetMessageAsync(msg.Id);
await TryRunCommand(guild, channel, msg);
//msg.DeleteAfter(5);
}
catch { }
@@ -216,8 +216,7 @@ public class CommandHandler : INService
var channel = msg.Channel;
var guild = (msg.Channel as SocketTextChannel)?.Guild;
await TryRunCommand(guild, channel, usrMsg)
.ConfigureAwait(false);
await TryRunCommand(guild, channel, usrMsg);
}
catch (Exception ex)
{
@@ -250,25 +249,25 @@ public class CommandHandler : INService
// execute the command and measure the time it took
if (messageContent.StartsWith(prefix, StringComparison.InvariantCulture) || isPrefixCommand)
{
var (success, error, info) = await ExecuteCommandAsync(new(_client, usrMsg), messageContent, isPrefixCommand ? 1 : prefix.Length, _services, MultiMatchHandling.Best).ConfigureAwait(false);
var (success, error, info) = await ExecuteCommandAsync(new(_client, usrMsg), messageContent, isPrefixCommand ? 1 : prefix.Length, _services, MultiMatchHandling.Best);
startTime = Environment.TickCount - startTime;
if (success)
{
await LogSuccessfulExecution(usrMsg, channel as ITextChannel, blockTime, startTime).ConfigureAwait(false);
await CommandExecuted(usrMsg, info).ConfigureAwait(false);
await LogSuccessfulExecution(usrMsg, channel as ITextChannel, blockTime, startTime);
await CommandExecuted(usrMsg, info);
return;
}
else if (error != null)
{
LogErroredExecution(error, usrMsg, channel as ITextChannel, blockTime, startTime);
if (guild != null)
await CommandErrored(info, channel as ITextChannel, error).ConfigureAwait(false);
await CommandErrored(info, channel as ITextChannel, error);
}
}
else
{
await OnMessageNoTrigger(usrMsg).ConfigureAwait(false);
await OnMessageNoTrigger(usrMsg);
}
await _behaviourExecutor.RunLateExecutorsAsync(guild, usrMsg);
@@ -289,7 +288,7 @@ public class CommandHandler : INService
foreach (var match in commands)
{
preconditionResults[match] = await match.Command.CheckPreconditionsAsync(context, services).ConfigureAwait(false);
preconditionResults[match] = await match.Command.CheckPreconditionsAsync(context, services);
}
var successfulPreconditions = preconditionResults
@@ -308,7 +307,7 @@ public class CommandHandler : INService
var parseResultsDict = new Dictionary<CommandMatch, ParseResult>();
foreach (var pair in successfulPreconditions)
{
var parseResult = await pair.Key.ParseAsync(context, searchResult, pair.Value, services).ConfigureAwait(false);
var parseResult = await pair.Key.ParseAsync(context, searchResult, pair.Value, services);
if (parseResult.Error == CommandError.MultipleMatches)
{
@@ -374,7 +373,7 @@ public class CommandHandler : INService
//If we get this far, at least one parse was successful. Execute the most likely overload.
var chosenOverload = successfulParses[0];
var execResult = (Discord.Commands.ExecuteResult)await chosenOverload.Key.ExecuteAsync(context, chosenOverload.Value, services).ConfigureAwait(false);
var execResult = (Discord.Commands.ExecuteResult)await chosenOverload.Key.ExecuteAsync(context, chosenOverload.Value, services);
if (execResult.Exception != null && (execResult.Exception is not HttpException he || he.DiscordCode != DiscordErrorCode.InsufficientPermissions))
{

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Common.ModuleBehaviors;
using Microsoft.Extensions.DependencyInjection;
@@ -77,7 +77,7 @@ public sealed class BehaviorExecutor : IBehaviourExecutor, INService
{
try
{
await exec.LateExecute(guild, usrMsg).ConfigureAwait(false);
await exec.LateExecute(guild, usrMsg);
}
catch (Exception ex)
{

View File

@@ -53,7 +53,7 @@ public class GoogleApiService : IGoogleApiService, INService
query.Type = "playlist";
query.Q = keywords;
return (await query.ExecuteAsync().ConfigureAwait(false)).Items.Select(i => i.Id.PlaylistId);
return (await query.ExecuteAsync()).Items.Select(i => i.Id.PlaylistId);
}
//private readonly Regex YtVideoIdRegex = new Regex(@"(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\?(?:\S*?&?v\=))|youtu\.be\/)(?<id>[a-zA-Z0-9_-]{6,11})", RegexOptions.Compiled);
@@ -73,7 +73,7 @@ public class GoogleApiService : IGoogleApiService, INService
query.MaxResults = count;
query.RelatedToVideoId = id;
query.Type = "video";
return (await query.ExecuteAsync().ConfigureAwait(false)).Items.Select(i => "http://www.youtube.com/watch?v=" + i.Id.VideoId);
return (await query.ExecuteAsync()).Items.Select(i => "http://www.youtube.com/watch?v=" + i.Id.VideoId);
}
public async Task<IEnumerable<string>> GetVideoLinksByKeywordAsync(string keywords, int count = 1)
@@ -90,7 +90,7 @@ public class GoogleApiService : IGoogleApiService, INService
query.Q = keywords;
query.Type = "video";
query.SafeSearch = SearchResource.ListRequest.SafeSearchEnum.Strict;
return (await query.ExecuteAsync().ConfigureAwait(false)).Items.Select(i => "http://www.youtube.com/watch?v=" + i.Id.VideoId);
return (await query.ExecuteAsync()).Items.Select(i => "http://www.youtube.com/watch?v=" + i.Id.VideoId);
}
public async Task<IEnumerable<(string Name, string Id, string Url)>> GetVideoInfosByKeywordAsync(string keywords, int count = 1)
@@ -106,7 +106,7 @@ public class GoogleApiService : IGoogleApiService, INService
query.MaxResults = count;
query.Q = keywords;
query.Type = "video";
return (await query.ExecuteAsync().ConfigureAwait(false)).Items.Select(i => (i.Snippet.Title.TrimTo(50), i.Id.VideoId, "http://www.youtube.com/watch?v=" + i.Id.VideoId));
return (await query.ExecuteAsync()).Items.Select(i => (i.Snippet.Title.TrimTo(50), i.Id.VideoId, "http://www.youtube.com/watch?v=" + i.Id.VideoId));
}
public Task<string> ShortenUrl(Uri url) => ShortenUrl(url.ToString());
@@ -122,7 +122,7 @@ public class GoogleApiService : IGoogleApiService, INService
try
{
var response = await sh.Url.Insert(new() { LongUrl = url }).ExecuteAsync().ConfigureAwait(false);
var response = await sh.Url.Insert(new() { LongUrl = url }).ExecuteAsync();
return response.Id;
}
catch (GoogleApiException ex) when (ex.HttpStatusCode == HttpStatusCode.Forbidden)
@@ -159,7 +159,7 @@ public class GoogleApiService : IGoogleApiService, INService
query.PlaylistId = playlistId;
query.PageToken = nextPageToken;
var data = await query.ExecuteAsync().ConfigureAwait(false);
var data = await query.ExecuteAsync();
toReturn.AddRange(data.Items.Select(i => i.ContentDetails.VideoId));
nextPageToken = data.NextPageToken;
@@ -188,7 +188,7 @@ public class GoogleApiService : IGoogleApiService, INService
var q = yt.Videos.List("contentDetails");
q.Id = string.Join(",", videoIdsList.Take(toGet));
videoIdsList = videoIdsList.Skip(toGet).ToList();
var items = (await q.ExecuteAsync().ConfigureAwait(false)).Items;
var items = (await q.ExecuteAsync()).Items;
foreach (var i in items)
{
toReturn.Add(i.Id, System.Xml.XmlConvert.ToTimeSpan(i.ContentDetails.Duration));
@@ -213,7 +213,7 @@ public class GoogleApiService : IGoogleApiService, INService
req.SearchType = CseResource.ListRequest.SearchTypeEnum.Image;
req.Start = new NadekoRandom().Next(0, 20);
var search = await req.ExecuteAsync().ConfigureAwait(false);
var search = await req.ExecuteAsync();
return new(search.Items[0].Image, search.Items[0].Link);
}
@@ -368,7 +368,7 @@ public class GoogleApiService : IGoogleApiService, INService
using (var http = _httpFactory.CreateClient())
{
http.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
text = await http.GetStringAsync(url).ConfigureAwait(false);
text = await http.GetStringAsync(url);
}
return string.Concat(JArray.Parse(text)[0].Select(x => x[0]));

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Newtonsoft.Json;
using StackExchange.Redis;
using System.Net;
@@ -32,7 +32,7 @@ public class RedisCache : IDataCache
public async Task<(bool Success, byte[] Data)> TryGetImageDataAsync(Uri key)
{
var _db = Redis.GetDatabase();
byte[] x = await _db.StringGetAsync("image_" + key).ConfigureAwait(false);
byte[] x = await _db.StringGetAsync("image_" + key);
return (x != null, x);
}
@@ -45,7 +45,7 @@ public class RedisCache : IDataCache
public async Task<(bool Success, string Data)> TryGetAnimeDataAsync(string key)
{
var _db = Redis.GetDatabase();
string x = await _db.StringGetAsync("anime_" + key).ConfigureAwait(false);
string x = await _db.StringGetAsync("anime_" + key);
return (x != null, x);
}
@@ -58,7 +58,7 @@ public class RedisCache : IDataCache
public async Task<(bool Success, string Data)> TryGetNovelDataAsync(string key)
{
var _db = Redis.GetDatabase();
string x = await _db.StringGetAsync("novel_" + key).ConfigureAwait(false);
string x = await _db.StringGetAsync("novel_" + key);
return (x != null, x);
}
@@ -173,16 +173,16 @@ public class RedisCache : IDataCache
{
var _db = Redis.GetDatabase();
var data = await _db.StringGetAsync(key).ConfigureAwait(false);
var data = await _db.StringGetAsync(key);
if (!data.HasValue)
{
var obj = await factory(param).ConfigureAwait(false);
var obj = await factory(param);
if (obj is null)
return default(TOut);
await _db.StringSetAsync(key, JsonConvert.SerializeObject(obj),
expiry: expiry).ConfigureAwait(false);
expiry: expiry);
return obj;
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Newtonsoft.Json;
using StackExchange.Redis;
using NadekoBot.Common.ModuleBehaviors;
@@ -215,7 +215,7 @@ public sealed class RedisImagesCache : IImageCache, IReadyExecutor
private async Task Load(ImageKeys key, Uri[] uris)
{
await Db.KeyDeleteAsync(GetRedisKey(key));
var imageData = await Task.WhenAll(uris.Select(GetImageData));
var imageData = await uris.Select(GetImageData).WhenAll();
var vals = imageData.Where(x => x is not null).Select(x => (RedisValue)x).ToArray();
await Db.ListRightPushAsync(GetRedisKey(key), vals);
@@ -260,7 +260,9 @@ public sealed class RedisImagesCache : IImageCache, IReadyExecutor
private async Task<bool> AllKeysExist()
{
var tasks = await Task.WhenAll(GetAllKeys().Select(x => Db.KeyExistsAsync(GetRedisKey(x))));
var tasks = await GetAllKeys()
.Select(x => Db.KeyExistsAsync(GetRedisKey(x)))
.WhenAll();
return tasks.All(exist => exist);
}

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Grpc.Core;
using NadekoBot.Common.ModuleBehaviors;
using NadekoBot.Coordinator;
@@ -98,7 +98,7 @@ public class RemoteGrpcCoordinator : ICoordinator, IReadyExecutor
break;
}
await Task.Delay(22500).ConfigureAwait(false);
await Task.Delay(22500);
}
catch (Exception ex)
{
@@ -106,7 +106,7 @@ public class RemoteGrpcCoordinator : ICoordinator, IReadyExecutor
break;
}
await Task.Delay(7500).ConfigureAwait(false);
await Task.Delay(7500);
}
Environment.Exit(5);

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Newtonsoft.Json;
namespace NadekoBot.Services;
@@ -19,7 +19,7 @@ public class SoundCloudApiService : INService
using (var http = _httpFactory.CreateClient())
{
response = await http.GetStringAsync($"https://scapi.nadeko.bot/resolve?url={url}").ConfigureAwait(false);
response = await http.GetStringAsync($"https://scapi.nadeko.bot/resolve?url={url}");
}
var responseObj = JsonConvert.DeserializeObject<SoundCloudVideo>(response);
@@ -37,7 +37,7 @@ public class SoundCloudApiService : INService
var response = string.Empty;
using (var http = _httpFactory.CreateClient())
{
response = await http.GetStringAsync(new Uri($"https://scapi.nadeko.bot/tracks?q={Uri.EscapeDataString(query)}")).ConfigureAwait(false);
response = await http.GetStringAsync(new Uri($"https://scapi.nadeko.bot/tracks?q={Uri.EscapeDataString(query)}"));
}
var responseObj = JsonConvert.DeserializeObject<SoundCloudVideo[]>(response)

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Common.ModuleBehaviors;
using System.Diagnostics;
@@ -132,7 +132,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
http.DefaultRequestHeaders.Add("Authorization", _creds.BotListToken);
using (await http.PostAsync(new Uri($"https://discordbots.org/api/bots/{client.CurrentUser.Id}/stats"), content).ConfigureAwait(false)) { }
using (await http.PostAsync(new Uri($"https://discordbots.org/api/bots/{client.CurrentUser.Id}/stats"), content)) { }
}
catch (Exception ex)
{

View File

@@ -40,8 +40,8 @@ public class YtdlOperation
Log.Debug($"Executing {process.StartInfo.FileName} {process.StartInfo.Arguments}");
process.Start();
var str = await process.StandardOutput.ReadToEndAsync().ConfigureAwait(false);
var err = await process.StandardError.ReadToEndAsync().ConfigureAwait(false);
var str = await process.StandardOutput.ReadToEndAsync();
var err = await process.StandardError.ReadToEndAsync();
if (!string.IsNullOrEmpty(err))
Log.Warning("YTDL warning: {YtdlWarning}", err);

View File

@@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Common.Configs;
using SixLabors.ImageSharp.PixelFormats;
@@ -31,7 +31,7 @@ public sealed class BotConfigService : ConfigServiceBase<BotConfig>
private void Migrate()
{
if (_data.Version < 2)
if (data.Version < 2)
{
ModifyConfig(c => c.Version = 2);
}

View File

@@ -1,4 +1,3 @@
#nullable disable
using System.Linq.Expressions;
using System.Reflection;
using NadekoBot.Common.Yml;
@@ -18,10 +17,10 @@ public abstract class ConfigServiceBase<TSettings> : IConfigService
protected readonly IPubSub _pubSub;
private readonly TypedKey<TSettings> _changeKey;
protected TSettings _data;
protected TSettings data;
// todo future config arrays are not copied - they're not protected from mutations
public TSettings Data => _data.Clone();
public TSettings Data => data.Clone();
public abstract string Name { get; }
@@ -40,16 +39,17 @@ public abstract class ConfigServiceBase<TSettings> : IConfigService
_pubSub = pubSub;
_changeKey = changeKey;
data = new();
Load();
_pubSub.Sub(_changeKey, OnChangePublished);
}
private void PublishChange()
=> _pubSub.Pub(_changeKey, _data);
=> _pubSub.Pub(_changeKey, data);
private ValueTask OnChangePublished(TSettings newData)
{
_data = newData;
data = newData;
OnStateUpdate();
return default;
}
@@ -62,11 +62,11 @@ public abstract class ConfigServiceBase<TSettings> : IConfigService
// if file is deleted, regenerate it with default values
if (!File.Exists(_filePath))
{
_data = new();
data = new();
Save();
}
_data = _serializer.Deserialize<TSettings>(File.ReadAllText(_filePath));
data = _serializer.Deserialize<TSettings>(File.ReadAllText(_filePath));
}
/// <summary>
@@ -75,12 +75,12 @@ public abstract class ConfigServiceBase<TSettings> : IConfigService
public void Reload()
{
Load();
_pubSub.Pub(_changeKey, _data);
_pubSub.Pub(_changeKey, data);
}
/// <summary>
/// Doesn't do anything by default. This method will be executed after
/// <see cref="_data"/> is reloaded from <see cref="_filePath"/> or new data is recieved
/// <see cref="data"/> is reloaded from <see cref="_filePath"/> or new data is recieved
/// from the publish event
/// </summary>
protected virtual void OnStateUpdate()
@@ -90,7 +90,7 @@ public abstract class ConfigServiceBase<TSettings> : IConfigService
private void Save()
{
var strData = _serializer.Serialize(_data);
var strData = _serializer.Serialize(data);
File.WriteAllText(_filePath, strData);
}
@@ -109,7 +109,7 @@ public abstract class ConfigServiceBase<TSettings> : IConfigService
checker ??= _ => true;
key = key.ToLowerInvariant();
_propPrinters[key] = obj => printer((TProp)obj);
_propSelectors[key] = () => selector.Compile()(_data);
_propSelectors[key] = () => selector.Compile()(data);
_propSetters[key] = Magic(selector, parser, checker);
_propComments[key] = ((MemberExpression)selector.Body).Member.GetCustomAttribute<CommentAttribute>()?.Comment;
}
@@ -192,7 +192,7 @@ public abstract class ConfigServiceBase<TSettings> : IConfigService
{
var copy = Data;
action(copy);
_data = copy;
data = copy;
Save();
PublishChange();
}