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 16 kB

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