You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChannelHelper.cs 15 kB

8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. using Discord.API.Rest;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.Immutable;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. using Model = Discord.API.Channel;
  9. using UserModel = Discord.API.User;
  10. namespace Discord.Rest
  11. {
  12. internal static class ChannelHelper
  13. {
  14. //General
  15. public static async Task DeleteAsync(IChannel channel, BaseDiscordClient client,
  16. RequestOptions options)
  17. {
  18. await client.ApiClient.DeleteChannelAsync(channel.Id, options).ConfigureAwait(false);
  19. }
  20. public static async Task<Model> ModifyAsync(IGuildChannel channel, BaseDiscordClient client,
  21. Action<GuildChannelProperties> func,
  22. RequestOptions options)
  23. {
  24. var args = new GuildChannelProperties();
  25. func(args);
  26. var apiArgs = new API.Rest.ModifyGuildChannelParams
  27. {
  28. Name = args.Name,
  29. Position = args.Position
  30. };
  31. return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false);
  32. }
  33. public static async Task<Model> ModifyAsync(ITextChannel channel, BaseDiscordClient client,
  34. Action<TextChannelProperties> func,
  35. RequestOptions options)
  36. {
  37. var args = new TextChannelProperties();
  38. func(args);
  39. var apiArgs = new API.Rest.ModifyTextChannelParams
  40. {
  41. Name = args.Name,
  42. Position = args.Position,
  43. Topic = args.Topic,
  44. IsNsfw = args.IsNsfw
  45. };
  46. return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false);
  47. }
  48. public static async Task<Model> ModifyAsync(IVoiceChannel channel, BaseDiscordClient client,
  49. Action<VoiceChannelProperties> func,
  50. RequestOptions options)
  51. {
  52. var args = new VoiceChannelProperties();
  53. func(args);
  54. var apiArgs = new API.Rest.ModifyVoiceChannelParams
  55. {
  56. Bitrate = args.Bitrate,
  57. Name = args.Name,
  58. Position = args.Position,
  59. UserLimit = args.UserLimit.IsSpecified ? (args.UserLimit.Value ?? 0) : Optional.Create<int>()
  60. };
  61. return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false);
  62. }
  63. //Invites
  64. public static async Task<IReadOnlyCollection<RestInviteMetadata>> GetInvitesAsync(IGuildChannel channel, BaseDiscordClient client,
  65. RequestOptions options)
  66. {
  67. var models = await client.ApiClient.GetChannelInvitesAsync(channel.Id, options).ConfigureAwait(false);
  68. return models.Select(x => RestInviteMetadata.Create(client, null, channel, x)).ToImmutableArray();
  69. }
  70. public static async Task<RestInviteMetadata> CreateInviteAsync(IGuildChannel channel, BaseDiscordClient client,
  71. int? maxAge, int? maxUses, bool isTemporary, bool isUnique, RequestOptions options)
  72. {
  73. var args = new CreateChannelInviteParams { IsTemporary = isTemporary, IsUnique = isUnique };
  74. if (maxAge.HasValue)
  75. args.MaxAge = maxAge.Value;
  76. else
  77. args.MaxAge = 0;
  78. if (maxUses.HasValue)
  79. args.MaxUses = maxUses.Value;
  80. else
  81. args.MaxUses = 0;
  82. var model = await client.ApiClient.CreateChannelInviteAsync(channel.Id, args, options).ConfigureAwait(false);
  83. return RestInviteMetadata.Create(client, null, channel, model);
  84. }
  85. //Messages
  86. public static async Task<RestMessage> GetMessageAsync(IMessageChannel channel, BaseDiscordClient client,
  87. ulong id, RequestOptions options)
  88. {
  89. var guildId = (channel as IGuildChannel)?.GuildId;
  90. var guild = guildId != null ? await (client as IDiscordClient).GetGuildAsync(guildId.Value, CacheMode.CacheOnly).ConfigureAwait(false) : null;
  91. var model = await client.ApiClient.GetChannelMessageAsync(channel.Id, id, options).ConfigureAwait(false);
  92. if (model == null)
  93. return null;
  94. var author = GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable());
  95. return RestMessage.Create(client, channel, author, model);
  96. }
  97. public static IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(IMessageChannel channel, BaseDiscordClient client,
  98. ulong? fromMessageId, Direction dir, int limit, RequestOptions options)
  99. {
  100. if (dir == Direction.Around)
  101. throw new NotImplementedException(); //TODO: Impl
  102. var guildId = (channel as IGuildChannel)?.GuildId;
  103. var guild = guildId != null ? (client as IDiscordClient).GetGuildAsync(guildId.Value, CacheMode.CacheOnly).Result : null;
  104. return new PagedAsyncEnumerable<RestMessage>(
  105. DiscordConfig.MaxMessagesPerBatch,
  106. async (info, ct) =>
  107. {
  108. var args = new GetChannelMessagesParams
  109. {
  110. RelativeDirection = dir,
  111. Limit = info.PageSize
  112. };
  113. if (info.Position != null)
  114. args.RelativeMessageId = info.Position.Value;
  115. var models = await client.ApiClient.GetChannelMessagesAsync(channel.Id, args, options).ConfigureAwait(false);
  116. var builder = ImmutableArray.CreateBuilder<RestMessage>();
  117. foreach (var model in models)
  118. {
  119. var author = GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable());
  120. builder.Add(RestMessage.Create(client, channel, author, model));
  121. }
  122. return builder.ToImmutable();
  123. },
  124. nextPage: (info, lastPage) =>
  125. {
  126. if (lastPage.Count != DiscordConfig.MaxMessagesPerBatch)
  127. return false;
  128. if (dir == Direction.Before)
  129. info.Position = lastPage.Min(x => x.Id);
  130. else
  131. info.Position = lastPage.Max(x => x.Id);
  132. return true;
  133. },
  134. start: fromMessageId,
  135. count: limit
  136. );
  137. }
  138. public static async Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(IMessageChannel channel, BaseDiscordClient client,
  139. RequestOptions options)
  140. {
  141. var guildId = (channel as IGuildChannel)?.GuildId;
  142. var guild = guildId != null ? await (client as IDiscordClient).GetGuildAsync(guildId.Value, CacheMode.CacheOnly).ConfigureAwait(false) : null;
  143. var models = await client.ApiClient.GetPinsAsync(channel.Id, options).ConfigureAwait(false);
  144. var builder = ImmutableArray.CreateBuilder<RestMessage>();
  145. foreach (var model in models)
  146. {
  147. var author = GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable());
  148. builder.Add(RestMessage.Create(client, channel, author, model));
  149. }
  150. return builder.ToImmutable();
  151. }
  152. public static async Task<RestUserMessage> SendMessageAsync(IMessageChannel channel, BaseDiscordClient client,
  153. string text, bool isTTS, Embed embed, RequestOptions options)
  154. {
  155. var args = new CreateMessageParams(text) { IsTTS = isTTS, Embed = embed?.ToModel() };
  156. var model = await client.ApiClient.CreateMessageAsync(channel.Id, args, options).ConfigureAwait(false);
  157. return RestUserMessage.Create(client, channel, client.CurrentUser, model);
  158. }
  159. #if FILESYSTEM
  160. public static async Task<RestUserMessage> SendFileAsync(IMessageChannel channel, BaseDiscordClient client,
  161. string filePath, string text, bool isTTS, RequestOptions options)
  162. {
  163. string filename = Path.GetFileName(filePath);
  164. using (var file = File.OpenRead(filePath))
  165. return await SendFileAsync(channel, client, file, filename, text, isTTS, options).ConfigureAwait(false);
  166. }
  167. #endif
  168. public static async Task<RestUserMessage> SendFileAsync(IMessageChannel channel, BaseDiscordClient client,
  169. Stream stream, string filename, string text, bool isTTS, RequestOptions options)
  170. {
  171. var args = new UploadFileParams(stream) { Filename = filename, Content = text, IsTTS = isTTS };
  172. var model = await client.ApiClient.UploadFileAsync(channel.Id, args, options).ConfigureAwait(false);
  173. return RestUserMessage.Create(client, channel, client.CurrentUser, model);
  174. }
  175. public static async Task DeleteMessagesAsync(ITextChannel channel, BaseDiscordClient client,
  176. IEnumerable<ulong> messageIds, RequestOptions options)
  177. {
  178. var msgs = messageIds.ToArray();
  179. if (msgs.Length < 100)
  180. {
  181. var args = new DeleteMessagesParams(msgs);
  182. await client.ApiClient.DeleteMessagesAsync(channel.Id, args, options).ConfigureAwait(false);
  183. }
  184. else
  185. {
  186. var batch = new ulong[100];
  187. for (int i = 0; i < (msgs.Length + 99) / 100; i++)
  188. {
  189. Array.Copy(msgs, i * 100, batch, 0, Math.Min(msgs.Length - (100 * i), 100));
  190. var args = new DeleteMessagesParams(batch);
  191. await client.ApiClient.DeleteMessagesAsync(channel.Id, args, options).ConfigureAwait(false);
  192. }
  193. }
  194. }
  195. //Permission Overwrites
  196. public static async Task AddPermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
  197. IUser user, OverwritePermissions perms, RequestOptions options)
  198. {
  199. var args = new ModifyChannelPermissionsParams("member", perms.AllowValue, perms.DenyValue);
  200. await client.ApiClient.ModifyChannelPermissionsAsync(channel.Id, user.Id, args, options).ConfigureAwait(false);
  201. }
  202. public static async Task AddPermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
  203. IRole role, OverwritePermissions perms, RequestOptions options)
  204. {
  205. var args = new ModifyChannelPermissionsParams("role", perms.AllowValue, perms.DenyValue);
  206. await client.ApiClient.ModifyChannelPermissionsAsync(channel.Id, role.Id, args, options).ConfigureAwait(false);
  207. }
  208. public static async Task RemovePermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
  209. IUser user, RequestOptions options)
  210. {
  211. await client.ApiClient.DeleteChannelPermissionAsync(channel.Id, user.Id, options).ConfigureAwait(false);
  212. }
  213. public static async Task RemovePermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
  214. IRole role, RequestOptions options)
  215. {
  216. await client.ApiClient.DeleteChannelPermissionAsync(channel.Id, role.Id, options).ConfigureAwait(false);
  217. }
  218. //Users
  219. public static async Task<RestGuildUser> GetUserAsync(IGuildChannel channel, IGuild guild, BaseDiscordClient client,
  220. ulong id, RequestOptions options)
  221. {
  222. var model = await client.ApiClient.GetGuildMemberAsync(channel.GuildId, id, options).ConfigureAwait(false);
  223. if (model == null)
  224. return null;
  225. var user = RestGuildUser.Create(client, guild, model);
  226. if (!user.GetPermissions(channel).ViewChannel)
  227. return null;
  228. return user;
  229. }
  230. public static IAsyncEnumerable<IReadOnlyCollection<RestGuildUser>> GetUsersAsync(IGuildChannel channel, IGuild guild, BaseDiscordClient client,
  231. ulong? fromUserId, int? limit, RequestOptions options)
  232. {
  233. return new PagedAsyncEnumerable<RestGuildUser>(
  234. DiscordConfig.MaxUsersPerBatch,
  235. async (info, ct) =>
  236. {
  237. var args = new GetGuildMembersParams
  238. {
  239. Limit = info.PageSize
  240. };
  241. if (info.Position != null)
  242. args.AfterUserId = info.Position.Value;
  243. var models = await client.ApiClient.GetGuildMembersAsync(guild.Id, args, options).ConfigureAwait(false);
  244. return models
  245. .Select(x => RestGuildUser.Create(client, guild, x))
  246. .Where(x => x.GetPermissions(channel).ViewChannel)
  247. .ToImmutableArray();
  248. },
  249. nextPage: (info, lastPage) =>
  250. {
  251. if (lastPage.Count != DiscordConfig.MaxMessagesPerBatch)
  252. return false;
  253. info.Position = lastPage.Max(x => x.Id);
  254. return true;
  255. },
  256. start: fromUserId,
  257. count: limit
  258. );
  259. }
  260. //Typing
  261. public static async Task TriggerTypingAsync(IMessageChannel channel, BaseDiscordClient client,
  262. RequestOptions options = null)
  263. {
  264. await client.ApiClient.TriggerTypingIndicatorAsync(channel.Id, options).ConfigureAwait(false);
  265. }
  266. public static IDisposable EnterTypingState(IMessageChannel channel, BaseDiscordClient client,
  267. RequestOptions options)
  268. => new TypingNotifier(client, channel, options);
  269. //Helpers
  270. private static IUser GetAuthor(BaseDiscordClient client, IGuild guild, UserModel model, ulong? webhookId)
  271. {
  272. IUser author = null;
  273. if (guild != null)
  274. author = guild.GetUserAsync(model.Id, CacheMode.CacheOnly).Result;
  275. if (author == null)
  276. author = RestUser.Create(client, guild, model, webhookId);
  277. return author;
  278. }
  279. public static bool IsNsfw(IChannel channel)
  280. => IsNsfw(channel.Name);
  281. public static bool IsNsfw(string channelName) =>
  282. channelName == "nsfw" || channelName.StartsWith("nsfw-");
  283. }
  284. }