Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -88,39 +88,19 @@ public static async Task<T> PostParametersAsForm<T>(this HttpClient httpClient,
return resObj;
}

public static async Task<T> PostParametersAsMultiPartFormData<T>(this HttpClient httpClient, IEnumerable<KeyValuePair<string, string>> parameters, Byte[] bytes, string api, Action<string> logger = null) where T: Response
// Slack's upload_url answers with plain text ("OK - <bytes>"), so only the status code matters.
public static async Task PostBytes(this HttpClient httpClient, string url, byte[] bytes, Action<string> logger = null)
{
var request = new HttpRequestMessage(HttpMethod.Post, api);

if (parameters != null && parameters.Any())
{
var formData = new MultipartFormDataContent();
foreach (KeyValuePair<string,string> param in parameters)
{
formData.Add(new StringContent(param.Value), param.Key);
}
formData.Add(new ByteArrayContent(bytes), "file", parameters.First(p => p.Key == "filename").Value);

request.Content = formData;
}

var response = await httpClient.SendAsync(request);
var response = await httpClient.PostAsync(url, new ByteArrayContent(bytes));
var responseContent = await response.Content.ReadAsStringAsync();

if (!response.IsSuccessStatusCode)
{
logger?.Invoke($"{response.StatusCode} \n {responseContent}");
}

ThrowIfRateLimited(response, responseContent);
response.EnsureSuccessStatusCode();

var resObj = JsonSerializer.Deserialize<T>(responseContent, JsonSerializerSettings);

if(!resObj.Ok)
throw new WellKnownSlackApiException(error: $"{resObj.Error}", responseContent:responseContent);

return resObj;
}

private static readonly TimeSpan DefaultRetryAfter = TimeSpan.FromSeconds(60);
Expand Down
13 changes: 10 additions & 3 deletions source/src/Slackbot.Net.SlackClients.Http/ISlackClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,12 +138,19 @@ public interface ISlackClient
Task<UserProfileResponse> UserProfile(string user);

/// <summary>
/// Scopes required: files.write
/// Uploads a file
/// Scopes required: files:write
/// Uploads text content as a file via files.getUploadURLExternal + files.completeUploadExternal.
/// Channels must be channel IDs (comma-separated). Only File.Id and File.Title are populated.
/// </summary>
/// <remarks>https://api.slack.com/methods/files.upload</remarks>
/// <remarks>https://docs.slack.dev/reference/methods/files.completeUploadExternal</remarks>
Task<FileUploadResponse> FilesUpload(FileUploadRequest fileupload);

/// <summary>
/// Scopes required: files:write
/// Uploads a file via files.getUploadURLExternal + files.completeUploadExternal.
/// Channels must be channel IDs (comma-separated). Only File.Id and File.Title are populated.
/// </summary>
/// <remarks>https://docs.slack.dev/reference/methods/files.completeUploadExternal</remarks>
Task<FileUploadResponse> FilesUpload(FileUploadMultiPartRequest req);

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ namespace Slackbot.Net.SlackClients.Http.Models.Responses.FileUpload;
public class FileUploadResponse : Response
{
public FileUploadFile File { get; set; }
public FileUploadFile[] Files { get; set; }
}

internal class FilesGetUploadUrlExternalResponse : Response
{
public string Upload_Url { get; set; }
public string File_Id { get; set; }
}

public class FileUploadFile
Expand Down
49 changes: 30 additions & 19 deletions source/src/Slackbot.Net.SlackClients.Http/SlackClient.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Slackbot.Net.SlackClients.Http.Extensions;
using Slackbot.Net.SlackClients.Http.Models.Requests.AssistantThreadsSetStatus;
Expand Down Expand Up @@ -222,40 +224,49 @@ public async Task<UserProfileResponse> UserProfile(string user)
/// <inheritdoc/>
public async Task<FileUploadResponse> FilesUpload(FileUploadRequest req)
{
var parameters = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("channels", req.Channels),
new KeyValuePair<string, string>("title", req.Title),
new KeyValuePair<string, string>("content", req.Content),
new KeyValuePair<string, string>("filename", req.Filename),
new KeyValuePair<string, string>("filetype", req.Filetype),
new KeyValuePair<string, string>("initial_comment", req.Initial_Comment),
new KeyValuePair<string, string>("thread_ts", req.Thread_Ts),
};
return await _client.PostParametersAsForm<FileUploadResponse>(parameters, "files.upload", s => _logger.LogTrace(s));
return await UploadExternal(Encoding.UTF8.GetBytes(req.Content), req.Filename, req.Title, req.Channels, req.Initial_Comment, req.Thread_Ts);
}

/// <inheritdoc/>
public async Task<FileUploadResponse> FilesUpload(FileUploadMultiPartRequest req)
{
return await UploadExternal(req.File, req.Filename, req.Title, req.Channels, req.Initial_Comment, req.Thread_Ts);
}

private async Task<FileUploadResponse> UploadExternal(byte[] bytes, string filename, string title, string channels, string initialComment, string threadTs)
{
var uploadUrlParameters = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("filename", filename),
new KeyValuePair<string, string>("length", bytes.Length.ToString()),
};
var uploadUrl = await _client.PostParametersAsForm<FilesGetUploadUrlExternalResponse>(uploadUrlParameters, "files.getUploadURLExternal", s => _logger.LogTrace(s));

await _client.PostBytes(uploadUrl.Upload_Url, bytes, s => _logger.LogTrace(s));

var parameters = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("channels", req.Channels),
new KeyValuePair<string, string>("title", req.Title),
new KeyValuePair<string, string>("filename", req.Filename),
new KeyValuePair<string, string>("files", JsonSerializer.Serialize(new[] { new { id = uploadUrl.File_Id, title = title ?? filename } })),
};

if (req.Initial_Comment is { })
if (channels is { })
{
parameters.Add(new KeyValuePair<string, string>("channels", channels));
}

if (initialComment is { })
{
parameters.Add(new KeyValuePair<string, string>("initial_comment", req.Initial_Comment));
parameters.Add(new KeyValuePair<string, string>("initial_comment", initialComment));
}

if (req.Thread_Ts is { })
if (threadTs is { })
{
parameters.Add(new KeyValuePair<string, string>("thread_ts", req.Thread_Ts));
parameters.Add(new KeyValuePair<string, string>("thread_ts", threadTs));
}

return await _client.PostParametersAsMultiPartFormData<FileUploadResponse>(parameters, req.File, "files.upload", s => _logger.LogTrace(s));
var response = await _client.PostParametersAsForm<FileUploadResponse>(parameters, "files.completeUploadExternal", s => _logger.LogTrace(s));
response.File = response.Files?.FirstOrDefault();
return response;
}

/// <inheritdoc/>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using System.Net;
using System.Text;
using Slackbot.Net.SlackClients.Http;
using Slackbot.Net.SlackClients.Http.Models.Requests.FileUpload;
using Slackbot.Net.Tests.Helpers;

namespace Slackbot.Net.Tests;

public class FileUploadExternalTests(ITestOutputHelper helper)
{
private readonly RoutingHttpMessageHandler _handler = new(new Dictionary<string, string>
{
["https://slack.com/api/files.getUploadURLExternal"] = """{ "ok": true, "upload_url": "https://files.slack.com/upload/v1/abc", "file_id": "F123" }""",
["https://files.slack.com/upload/v1/abc"] = "OK - 5",
["https://slack.com/api/files.completeUploadExternal"] = """{ "ok": true, "files": [{ "id": "F123", "title": "beer" }] }""",
});

private ISlackClient Client => new SlackClient(
new HttpClient(_handler) { BaseAddress = new Uri("https://slack.com/api/") },
new XUnitLogger<ISlackClient>(helper));

[Fact]
public async Task FilesUpload_Bytes_GetsUrl_Uploads_ThenCompletes()
{
var response = await Client.FilesUpload(new FileUploadMultiPartRequest
{
Channels = "C123",
File = [1, 2, 3, 4, 5],
Filename = "beer.png",
Title = "beer",
Thread_Ts = "1.2"
});

Assert.Equal("F123", response.File.Id);
Assert.Collection(_handler.Requests,
r => Assert.Equal("filename=beer.png&length=5", r.FormBody),
r => Assert.Equal(new byte[] { 1, 2, 3, 4, 5 }, r.Body),
r => Assert.Equal("""files=[{"id":"F123","title":"beer"}]&channels=C123&thread_ts=1.2""", r.FormBody));
}

[Fact]
public async Task FilesUpload_Content_UploadsUtf8_AndTitleFallsBackToFilename()
{
await Client.FilesUpload(new FileUploadRequest { Content = "hello", Filename = "hi.txt" });

Assert.Equal("hello", Encoding.UTF8.GetString(_handler.Requests[1].Body));
Assert.Equal("""files=[{"id":"F123","title":"hi.txt"}]""", _handler.Requests[2].FormBody);
}

private class RoutingHttpMessageHandler(Dictionary<string, string> responsesByUrl) : HttpMessageHandler
{
public List<(byte[] Body, string FormBody)> Requests { get; } = [];

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var body = await request.Content!.ReadAsByteArrayAsync(cancellationToken);
Requests.Add((body, WebUtility.UrlDecode(Encoding.UTF8.GetString(body))));
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(responsesByUrl[request.RequestUri!.ToString()]) };
}
}
}
Loading