Extensions.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using CardCollector.DataBase.Entity;
  9. using CardCollector.DataBase.EntityDao;
  10. using CardCollector.Resources;
  11. using Microsoft.EntityFrameworkCore;
  12. using Telegram.Bot.Types.InlineQueryResults;
  13. namespace CardCollector
  14. {
  15. public static class Extensions
  16. {
  17. /* Преобразует список стикеров в список результатов для телеграм */
  18. public static IEnumerable<InlineQueryResult> ToTelegramResults
  19. (this IEnumerable<StickerEntity> list, string command, bool asMessage = true)
  20. {
  21. var result = new List<InlineQueryResult>();
  22. foreach (var item in list)
  23. {
  24. result.Add( asMessage
  25. ? new InlineQueryResultCachedSticker($"{(Constants.UNLIMITED_ALL_STICKERS ? Command.unlimited_stickers : "")}" +
  26. $"{command}={item.Md5Hash}", item.Id)
  27. {InputMessageContent = new InputTextMessageContent(Text.select)}
  28. : new InlineQueryResultCachedSticker($"{(Constants.UNLIMITED_ALL_STICKERS ? Command.unlimited_stickers : "")}" +
  29. $"{command}={item.Md5Hash}", item.Id));
  30. /* Ограничение Telegram API по количеству результатов в 50 шт. */
  31. if (result.Count > 49) return result;
  32. }
  33. return result;
  34. }
  35. /* Преобразует список продавцов в список результатов для телеграм */
  36. public static async Task<IEnumerable<InlineQueryResult>> ToTelegramResults
  37. (this IEnumerable<AuctionEntity> list, string command)
  38. {
  39. var result = new List<InlineQueryResult>();
  40. foreach (var item in list)
  41. {
  42. var user = await UserDao.GetById(item.Trader);
  43. result.Add(new InlineQueryResultArticle($"{command}={item.Id}",
  44. $"{user.Username} {item.Count}{Text.items}", new InputTextMessageContent(Text.buy))
  45. { Description = $"{item.Price}{Text.gem} {Text.per} 1{Text.items}" });
  46. /* Ограничение Telegram API по количеству результатов в 50 шт. */
  47. if (result.Count > 49) return result;
  48. }
  49. return result;
  50. }
  51. /* Возвращает все стикеры системы */
  52. public static async Task<IEnumerable<StickerEntity>> ToStickers
  53. (this Dictionary<string, UserStickerRelationEntity> dict, string filter)
  54. {
  55. var result = new List<StickerEntity>();
  56. foreach (var relation in dict.Values.Where(i => i.Count > 0))
  57. {
  58. var sticker = await StickerDao.GetStickerByHash(relation.StickerId);
  59. if (sticker.Title.Contains(filter, StringComparison.CurrentCultureIgnoreCase)) result.Add(sticker);
  60. }
  61. return result;
  62. }
  63. public static async Task<IEnumerable<T>> WhereAsync<T>(
  64. this IEnumerable<T> source, Func<T, Task<bool>> predicate)
  65. {
  66. var results = new ConcurrentQueue<T>();
  67. var tasks = source.Select(
  68. async x =>
  69. {
  70. if (await predicate(x))
  71. results.Enqueue(x);
  72. });
  73. await Task.WhenAll(tasks);
  74. return results;
  75. }
  76. public static async Task<bool> AnyAsync<T>(
  77. this IEnumerable<T> source, Func<T, Task<bool>> predicate)
  78. {
  79. foreach (var element in source)
  80. if (await predicate(element)) return true;
  81. return false;
  82. }
  83. public static async Task<IEnumerable<TSource>> WhereAsync<TSource>(
  84. [NotNull] this IQueryable<TSource> source,
  85. [NotNull] Func<TSource, bool> predicate,
  86. CancellationToken cancellationToken = default)
  87. {
  88. var results = new ConcurrentQueue<TSource>();
  89. await foreach (var element in source.AsAsyncEnumerable().WithCancellation(cancellationToken))
  90. {
  91. if (predicate(element)) results.Enqueue(element);
  92. }
  93. return results;
  94. }
  95. public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> source)
  96. {
  97. return source.Select((item, index) => (item, index));
  98. }
  99. public static async Task<int> SumAsync<TSource>(this IEnumerable<TSource> source, Func<TSource, Task<int>> selector)
  100. {
  101. var sum = 0;
  102. checked
  103. {
  104. foreach (var item in source) sum += await selector(item);
  105. }
  106. return sum;
  107. }
  108. }
  109. }