Cleanup and minor fixes

pull/321/head
Alexey Golub 5 years ago
parent 247f3a9c5b
commit 4a35a7b530

@ -49,35 +49,42 @@ namespace DiscordChatExporter.Domain.Discord
{ {
} }
private async Task<JsonElement> GetApiResponseAsync(string url) private async Task<HttpResponseMessage> GetResponseAsync(string url)
{ {
using var response = await _httpRequestPolicy.ExecuteAsync(async () => return await _httpRequestPolicy.ExecuteAsync(async () =>
{ {
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_baseUri, url)); using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_baseUri, url));
request.Headers.Authorization = _token.GetAuthorizationHeader(); request.Headers.Authorization = _token.GetAuthorizationHeader();
return await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); return await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
}); });
}
if (response.StatusCode == HttpStatusCode.Unauthorized) private async Task<JsonElement> GetJsonResponseAsync(string url)
throw DiscordChatExporterException.Unauthorized(); {
using var response = await GetResponseAsync(url);
if ((int) response.StatusCode >= 400) if (!response.IsSuccessStatusCode)
throw DiscordChatExporterException.FailedHttpRequest(response); {
throw response.StatusCode switch
{
HttpStatusCode.Unauthorized => DiscordChatExporterException.Unauthorized(),
HttpStatusCode.Forbidden => DiscordChatExporterException.Forbidden(),
HttpStatusCode.NotFound => DiscordChatExporterException.NotFound(),
_ => DiscordChatExporterException.FailedHttpRequest(response)
};
}
return await response.Content.ReadAsJsonAsync(); return await response.Content.ReadAsJsonAsync();
} }
private async Task<JsonElement?> TryGetApiResponseAsync(string url) private async Task<JsonElement?> TryGetJsonResponseAsync(string url)
{ {
try using var response = await GetResponseAsync(url);
{
return await GetApiResponseAsync(url); return response.IsSuccessStatusCode
} ? await response.Content.ReadAsJsonAsync()
catch (DiscordChatExporterException) : (JsonElement?) null;
{
return null;
}
} }
public async IAsyncEnumerable<Guild> GetUserGuildsAsync() public async IAsyncEnumerable<Guild> GetUserGuildsAsync()
@ -93,7 +100,7 @@ namespace DiscordChatExporter.Domain.Discord
.SetQueryParameterIfNotNullOrWhiteSpace("after", afterId) .SetQueryParameterIfNotNullOrWhiteSpace("after", afterId)
.Build(); .Build();
var response = await GetApiResponseAsync(url); var response = await GetJsonResponseAsync(url);
var isEmpty = true; var isEmpty = true;
foreach (var guildJson in response.EnumerateArray()) foreach (var guildJson in response.EnumerateArray())
@ -115,7 +122,7 @@ namespace DiscordChatExporter.Domain.Discord
if (guildId == Guild.DirectMessages.Id) if (guildId == Guild.DirectMessages.Id)
return Guild.DirectMessages; return Guild.DirectMessages;
var response = await GetApiResponseAsync($"guilds/{guildId}"); var response = await GetJsonResponseAsync($"guilds/{guildId}");
return Guild.Parse(response); return Guild.Parse(response);
} }
@ -123,13 +130,13 @@ namespace DiscordChatExporter.Domain.Discord
{ {
if (guildId == Guild.DirectMessages.Id) if (guildId == Guild.DirectMessages.Id)
{ {
var response = await GetApiResponseAsync("users/@me/channels"); var response = await GetJsonResponseAsync("users/@me/channels");
foreach (var channelJson in response.EnumerateArray()) foreach (var channelJson in response.EnumerateArray())
yield return Channel.Parse(channelJson); yield return Channel.Parse(channelJson);
} }
else else
{ {
var response = await GetApiResponseAsync($"guilds/{guildId}/channels"); var response = await GetJsonResponseAsync($"guilds/{guildId}/channels");
var categories = response var categories = response
.EnumerateArray() .EnumerateArray()
@ -161,12 +168,10 @@ namespace DiscordChatExporter.Domain.Discord
if (guildId == Guild.DirectMessages.Id) if (guildId == Guild.DirectMessages.Id)
yield break; yield break;
var response = await GetApiResponseAsync($"guilds/{guildId}/roles"); var response = await GetJsonResponseAsync($"guilds/{guildId}/roles");
foreach (var roleJson in response.EnumerateArray()) foreach (var roleJson in response.EnumerateArray())
{
yield return Role.Parse(roleJson); yield return Role.Parse(roleJson);
}
} }
public async Task<Member?> TryGetGuildMemberAsync(string guildId, User user) public async Task<Member?> TryGetGuildMemberAsync(string guildId, User user)
@ -174,19 +179,19 @@ namespace DiscordChatExporter.Domain.Discord
if (guildId == Guild.DirectMessages.Id) if (guildId == Guild.DirectMessages.Id)
return Member.CreateForUser(user); return Member.CreateForUser(user);
var response = await TryGetApiResponseAsync($"guilds/{guildId}/members/{user.Id}"); var response = await TryGetJsonResponseAsync($"guilds/{guildId}/members/{user.Id}");
return response?.Pipe(Member.Parse); return response?.Pipe(Member.Parse);
} }
private async Task<string> GetChannelCategoryAsync(string channelParentId) private async Task<string> GetChannelCategoryAsync(string channelParentId)
{ {
var response = await GetApiResponseAsync($"channels/{channelParentId}"); var response = await GetJsonResponseAsync($"channels/{channelParentId}");
return response.GetProperty("name").GetString(); return response.GetProperty("name").GetString();
} }
public async Task<Channel> GetChannelAsync(string channelId) public async Task<Channel> GetChannelAsync(string channelId)
{ {
var response = await GetApiResponseAsync($"channels/{channelId}"); var response = await GetJsonResponseAsync($"channels/{channelId}");
var parentId = response.GetPropertyOrNull("parent_id")?.GetString(); var parentId = response.GetPropertyOrNull("parent_id")?.GetString();
var category = !string.IsNullOrWhiteSpace(parentId) var category = !string.IsNullOrWhiteSpace(parentId)
@ -204,7 +209,7 @@ namespace DiscordChatExporter.Domain.Discord
.SetQueryParameterIfNotNullOrWhiteSpace("before", before?.ToSnowflake()) .SetQueryParameterIfNotNullOrWhiteSpace("before", before?.ToSnowflake())
.Build(); .Build();
var response = await GetApiResponseAsync(url); var response = await GetJsonResponseAsync(url);
return response.EnumerateArray().Select(Message.Parse).LastOrDefault(); return response.EnumerateArray().Select(Message.Parse).LastOrDefault();
} }
@ -230,7 +235,7 @@ namespace DiscordChatExporter.Domain.Discord
.SetQueryParameter("after", afterId) .SetQueryParameter("after", afterId)
.Build(); .Build();
var response = await GetApiResponseAsync(url); var response = await GetJsonResponseAsync(url);
var messages = response var messages = response
.EnumerateArray() .EnumerateArray()

@ -25,14 +25,14 @@ namespace DiscordChatExporter.Domain.Discord.Models
public partial class Guild public partial class Guild
{ {
private static string GetIconUrl(string? id, string? iconHash) =>
!string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(iconHash)
? $"https://cdn.discordapp.com/icons/{id}/{iconHash}.png"
: "https://cdn.discordapp.com/embed/avatars/0.png";
public static Guild DirectMessages { get; } = public static Guild DirectMessages { get; } =
new Guild("@me", "Direct Messages", null); new Guild("@me", "Direct Messages", null);
private static string GetIconUrl(string id, string? iconHash) =>
!string.IsNullOrWhiteSpace(iconHash)
? $"https://cdn.discordapp.com/icons/{id}/{iconHash}.png"
: "https://cdn.discordapp.com/embed/avatars/0.png";
public static Guild Parse(JsonElement json) public static Guild Parse(JsonElement json)
{ {
var id = json.GetProperty("id").GetString(); var id = json.GetProperty("id").GetString();

@ -35,15 +35,15 @@ Failed to perform an HTTP request.
return new DiscordChatExporterException(message); return new DiscordChatExporterException(message);
} }
internal static DiscordChatExporterException ChannelForbidden(string channel) internal static DiscordChatExporterException Forbidden()
{ {
var message = $"Access to channel '{channel}' is forbidden."; const string message = "Access is forbidden.";
return new DiscordChatExporterException(message); return new DiscordChatExporterException(message);
} }
internal static DiscordChatExporterException ChannelDoesNotExist(string channel) internal static DiscordChatExporterException NotFound()
{ {
var message = $"Channel '{channel}' does not exist."; const string message = "Not found.";
return new DiscordChatExporterException(message); return new DiscordChatExporterException(message);
} }

@ -39,7 +39,7 @@ namespace DiscordChatExporter.Domain.Exporting
private async Task<MessageWriter> GetWriterAsync() private async Task<MessageWriter> GetWriterAsync()
{ {
// Ensure partition limit is not exceeded // Ensure partition limit has not been exceeded
if (IsPartitionLimitReached()) if (IsPartitionLimitReached())
{ {
await ResetWriterAsync(); await ResetWriterAsync();

@ -5,7 +5,6 @@ using DiscordChatExporter.Domain.Discord.Models;
namespace DiscordChatExporter.Domain.Exporting namespace DiscordChatExporter.Domain.Exporting
{ {
// Used for grouping contiguous messages in HTML export // Used for grouping contiguous messages in HTML export
internal partial class MessageGroup internal partial class MessageGroup
{ {
public User Author { get; } public User Author { get; }

@ -23,7 +23,11 @@ namespace DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors
public override MarkdownNode VisitMention(MentionNode mention) public override MarkdownNode VisitMention(MentionNode mention)
{ {
if (mention.Type == MentionType.User) if (mention.Type == MentionType.Meta)
{
_buffer.Append($"@{mention.Id}");
}
else if (mention.Type == MentionType.User)
{ {
var member = _context.TryGetMentionedMember(mention.Id); var member = _context.TryGetMentionedMember(mention.Id);
var name = member?.User.Name ?? "Unknown"; var name = member?.User.Name ?? "Unknown";

Loading…
Cancel
Save