Code cleanup

This commit is contained in:
2022-01-22 17:13:38 +03:00
parent 401f9fb529
commit ff63d6dfaa
13 changed files with 232 additions and 138 deletions
+7 -5
View File
@@ -1,4 +1,6 @@
using System;
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
@@ -107,7 +109,7 @@ namespace Kruzya.TelegramBot.Core
/// </summary>
/// <param name="path">The full path to assembly file</param>
/// <returns><see cref="IEnumerable{T}"/> if success, null otherwise.</returns>
private IEnumerable<Type> LoadAssembly(string path)
private IEnumerable<Type>? LoadAssembly(string path)
{
Assembly assembly;
try
@@ -150,7 +152,7 @@ namespace Kruzya.TelegramBot.Core
var module = _modules.FirstOrDefault(module => module.GetType() == moduleType);
if (module == null)
{
module = (Module) Activator.CreateInstance(moduleType, this);
module = (Module) Activator.CreateInstance(moduleType, this)!;
Console.WriteLine($"Started module {module.GetType().Name}");
_modules.Add(module);
}
@@ -169,12 +171,12 @@ namespace Kruzya.TelegramBot.Core
var possiblePaths = new List<string>();
if (args.RequestingAssembly != null)
{
var modulePath = Path.GetDirectoryName(args.RequestingAssembly.Location);
var modulePath = Path.GetDirectoryName(args.RequestingAssembly.Location)!;
possiblePaths.Add(modulePath);
possiblePaths.Add(args.RequestingAssembly.Location.Replace(".dll", ""));
}
possiblePaths.Add(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
possiblePaths.Add(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!);
possiblePaths.Add(Environment.CurrentDirectory);
foreach (var basePath in possiblePaths)
+2 -1
View File
@@ -4,6 +4,7 @@ using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Xml.Serialization;
namespace Kruzya.TelegramBot.Core.Data
@@ -35,7 +36,7 @@ namespace Kruzya.TelegramBot.Core.Data
public void SetValue<T>(T value)
{
Value = JsonSerializer.SerializeToUtf8Bytes(value, new JsonSerializerOptions { WriteIndented = false,
IgnoreNullValues = true });
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull });
ValueType = value.GetType().FullName;
}
}
+40
View File
@@ -0,0 +1,40 @@
using System;
using Microsoft.EntityFrameworkCore;
namespace Kruzya.TelegramBot.Core.Extensions;
public static class DbContextExtension
{
/// <summary>
/// Marks the entity as created.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="entity">Entity for marking as created.</param>
[Obsolete("DbContextExtension.MarkAsCreated is obsolete, use DbSet<T>.Add instead")]
public static void MarkAsCreated(this DbContext dbContext, object entity) =>
dbContext.Entry(entity).State = EntityState.Added;
/// <summary>
/// Marks the entity as deleted.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="entity">Entity for marking as deleted.</param>
[Obsolete("DbContextExtension.MarkAsDeleted is obsolete, use DbSet<T>.Remove instead")]
public static void MarkAsDeleted(this DbContext dbContext, object entity) =>
dbContext.Entry(entity).State = EntityState.Deleted;
/// <summary>
/// Marks the entity as modified.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="entity">Entity for marking as modified.</param>
[Obsolete("DbContextExtension.MarkAsModified is obsolete, use DbContext.Update instead")]
public static void MarkAsModified(this DbContext dbContext, object entity)
{
var entry = dbContext.Entry(entity);
if (entry.State == EntityState.Added)
return;
entry.State = EntityState.Modified;
}
}
@@ -0,0 +1,87 @@
using System.Threading.Tasks;
using Kruzya.TelegramBot.Core.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace Kruzya.TelegramBot.Core.Extensions
{
public static partial class RepositoryExtension
{
#region BotUser
public static async Task<BotUser> FindOrCreate(this DbSet<BotUser> repository, long chatId, long userId)
{
var user = await repository.SingleOrDefaultAsync(e => e.ChatId == chatId && e.UserId == userId);
if (user == null)
{
user = repository.Create();
user.ChatId = chatId;
user.UserId = userId;
}
return user;
}
#endregion
#region BotUserValue
#region FindOption
public static async Task<BotUserValue> FindOption(this DbSet<BotUserValue> repository, long chatId,
string option) => await repository.FindOption(chatId, 0, option);
public static async Task<BotUserValue> FindOption(this DbSet<BotUserValue> repository, BotUser user,
string option) => await repository.FindOption(user.ChatId, user.UserId, option);
public static async Task<BotUserValue> FindOption(this DbSet<BotUserValue> repository, long chatId, long userId,
string option) => await repository.SingleOrDefaultAsync(e =>
e.BotUser.ChatId == chatId && e.BotUser.UserId == userId && e.Name == option);
#endregion
#region FindOrCreateOption
public static async Task<BotUserValue> FindOrCreateOption(this DbSet<BotUserValue> repository, long chatId,
string option) => await repository.FindOrCreateOption(chatId, 0, option);
public static async Task<BotUserValue> FindOrCreateOption(this DbSet<BotUserValue> repository, BotUser user,
string option) => await repository.FindOrCreateOption(user.ChatId, user.UserId, option);
public static async Task<BotUserValue> FindOrCreateOption(this DbSet<BotUserValue> repository, long chatId,
long userId, string option)
{
var opt = await repository.FindOption(chatId, userId, option);
if (opt == null)
{
opt = repository.Create();
opt.Name = option;
opt.BotUser = await repository.GetService<CoreContext>().Users.FindOrCreate(chatId, userId);
}
return opt;
}
#endregion
#region SetOptionValue
public static async Task SetOptionValue<T>(this DbSet<BotUserValue> repository, long chatId, string option,
T val) => await repository.SetOptionValue(chatId, 0, option, val);
public static async Task SetOptionValue<T>(this DbSet<BotUserValue> repository, BotUser user, string option,
T val) => await repository.SetOptionValue(user.ChatId, user.UserId, option, val);
public static async Task SetOptionValue<T>(this DbSet<BotUserValue> repository, long chatId, long userId,
string option, T val)
{
var opt = await repository.FindOrCreateOption(chatId, userId, option);
opt.SetValue(val);
repository.Update(opt);
}
#endregion
#endregion
}
}
+1 -120
View File
@@ -5,44 +5,8 @@ using Microsoft.EntityFrameworkCore.Infrastructure;
namespace Kruzya.TelegramBot.Core.Extensions
{
public static class RepositoryExtension
public static partial class RepositoryExtension
{
#region DbContext
/// <summary>
/// Marks the entity as created.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="entity">Entity for marking as created.</param>
public static void MarkAsCreated(this DbContext dbContext, object entity) =>
dbContext.Entry(entity).State = EntityState.Added;
/// <summary>
/// Marks the entity as deleted.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="entity">Entity for marking as deleted.</param>
public static void MarkAsDeleted(this DbContext dbContext, object entity) =>
dbContext.Entry(entity).State = EntityState.Deleted;
/// <summary>
/// Marks the entity as modified.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="entity">Entity for marking as modified.</param>
public static void MarkAsModified(this DbContext dbContext, object entity)
{
var entry = dbContext.Entry(entity);
if (entry.State == EntityState.Added)
return;
entry.State = EntityState.Modified;
}
#endregion
#region Repository
public static TEntity Create<TEntity>(this DbSet<TEntity> repository) where TEntity : class, new()
{
var entity = new TEntity();
@@ -50,88 +14,5 @@ namespace Kruzya.TelegramBot.Core.Extensions
return entity;
}
#endregion
#region Core-context repository extensions
#region BotUser
public static async Task<BotUser> FindOrCreate(this DbSet<BotUser> repository, long chatId, long userId)
{
var user = await repository.SingleOrDefaultAsync(e => e.ChatId == chatId && e.UserId == userId);
if (user == null)
{
user = repository.Create();
user.ChatId = chatId;
user.UserId = userId;
}
return user;
}
#endregion
#region BotUserValue
#region FindOption
public static async Task<BotUserValue> FindOption(this DbSet<BotUserValue> repository, long chatId,
string option) => await repository.FindOption(chatId, 0, option);
public static async Task<BotUserValue> FindOption(this DbSet<BotUserValue> repository, BotUser user,
string option) => await repository.FindOption(user.ChatId, user.UserId, option);
public static async Task<BotUserValue> FindOption(this DbSet<BotUserValue> repository, long chatId, long userId,
string option) => await repository.SingleOrDefaultAsync(e =>
e.BotUser.ChatId == chatId && e.BotUser.UserId == userId && e.Name == option);
#endregion
#region FindOrCreateOption
public static async Task<BotUserValue> FindOrCreateOption(this DbSet<BotUserValue> repository, long chatId,
string option) => await repository.FindOrCreateOption(chatId, 0, option);
public static async Task<BotUserValue> FindOrCreateOption(this DbSet<BotUserValue> repository, BotUser user,
string option) => await repository.FindOrCreateOption(user.ChatId, user.UserId, option);
public static async Task<BotUserValue> FindOrCreateOption(this DbSet<BotUserValue> repository, long chatId,
long userId, string option)
{
var opt = await repository.FindOption(chatId, userId, option);
if (opt == null)
{
opt = repository.Create();
opt.Name = option;
opt.BotUser = await repository.GetService<CoreContext>().Users.FindOrCreate(chatId, userId);
}
return opt;
}
#endregion
#region SetOptionValue
public static async Task SetOptionValue<T>(this DbSet<BotUserValue> repository, long chatId, string option,
T val) => await repository.SetOptionValue(chatId, 0, option, val);
public static async Task SetOptionValue<T>(this DbSet<BotUserValue> repository, BotUser user, string option,
T val) => await repository.SetOptionValue(user.ChatId, user.UserId, option, val);
public static async Task SetOptionValue<T>(this DbSet<BotUserValue> repository, long chatId, long userId,
string option, T val)
{
var opt = await repository.FindOrCreateOption(chatId, userId, option);
opt.SetValue(val);
repository.Update(opt);
}
#endregion
#endregion
#endregion
}
}
+83
View File
@@ -0,0 +1,83 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace Kruzya.TelegramBot.Core.Service;
internal class EntityFormatter
{
private static readonly Dictionary<MessageEntityType, string> HtmlMap = new()
{
{ MessageEntityType.Bold, "<b>{0}</b>" },
{ MessageEntityType.Code, "<code>{0}</code>" },
{ MessageEntityType.Italic, "<i>{0}</i>" },
{ MessageEntityType.TextMention, "<a href=\"tg://user?id={1}\">{0}</a>" },
{ MessageEntityType.Pre, "<pre>{0}</pre>" },
{ MessageEntityType.Underline, "<u>{0}</u>" },
{ MessageEntityType.TextLink, "<a href=\"{1}\">{0}</a>" }
};
private static readonly Dictionary<MessageEntityType, string> MarkdownMap = new()
{
{ MessageEntityType.Bold, "*{0}*" },
{ MessageEntityType.Code, "```{0}```" },
{ MessageEntityType.Italic, "_{0}_" },
{ MessageEntityType.TextMention, "[{0}](tg://user?id={1})" },
{ MessageEntityType.Pre, "```{0}```" },
{ MessageEntityType.Underline, "__{0}__" },
{ MessageEntityType.TextLink, "[{0}]({1})" }
};
/// <summary>
/// Performs the formatting a text representation of message from <see cref="Message"/> entity with
/// </summary>
/// <param name="msg"></param>
/// <param name="parseMode"></param>
/// <returns></returns>
public string? FormatMessage(Message msg, ParseMode parseMode = ParseMode.Html)
{
var text = "";
var entities = msg.Entities;
if (entities != null)
{
// Suppress the warning about possibility using empty ref (CS8602).
text = msg.Text!;
// TODO: Currently, this algo don't support inherited entities. This need thinking.
foreach (var entity in entities.Reverse())
{
var entityText = text.Substring(entity.Offset, entity.Length);
text = text.Replace(entityText, FormatEntity(entity, entityText, parseMode));
}
}
return text;
}
public string FormatEntity(MessageEntity entity, string text, ParseMode parseMode)
{
var dict = parseMode switch
{
ParseMode.Html => HtmlMap,
ParseMode.Markdown => MarkdownMap,
ParseMode.MarkdownV2 => MarkdownMap,
_ => throw new Exception("Unsupported parse mode")
};
var arg = entity.Type switch
{
MessageEntityType.TextMention => entity.User!.Id.ToString(),
MessageEntityType.TextLink => entity.Url!,
_ => ""
};
return dict[entity.Type].Replace("{0}", text)
.Replace("{1}", arg);
}
}