forked from revenz/FileFlows
/
FileUploader.cs
177 lines (152 loc) · 6.62 KB
/
FileUploader.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Web;
using FileFlows.Plugin;
using HttpMethod = System.Net.Http.HttpMethod;
namespace FileFlows.ServerShared.FileServices;
/// <summary>
/// Provides methods to upload files along with their hashes for integrity verification.
/// </summary>
public class FileUploader
{
/// <summary>
/// The logger used for log messages
/// </summary>
private readonly ILogger logger;
/// <summary>
/// The URL where the file will be uploaded.
/// </summary>
private readonly string serverUrl;
/// <summary>
/// The UID of the executor for the authentication
/// </summary>
private readonly Guid executorUid;
/// <summary>
/// Constructs an instance of the file uploader
/// </summary>
/// <param name="logger">the logger to use in the file uploader</param>
/// <param name="serverUrl">The URL where the file will be uploaded.</param>
/// <param name="executorUid">The UID of the executor for the authentication</param>
public FileUploader(ILogger logger, string serverUrl, Guid executorUid)
{
this.logger = logger;
this.serverUrl = serverUrl;
this.executorUid = executorUid;
}
/// <summary>
/// Static HttpClient instance used for file uploading operations.
/// </summary>
private static readonly HttpClient _client;
/// <summary>
/// Static constructor
/// </summary>
static FileUploader()
{
HttpClientHandler handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
_client = new HttpClient(handler);
_client.Timeout = Timeout.InfiniteTimeSpan;
}
/// <summary>
/// Uploads a file to the specified URL, along with its hash for integrity verification.
/// </summary>
/// <param name="filePath">The path of the file to be uploaded.</param>
/// <param name="serverPath">The path on the server where the file will be saved.</param>
/// <returns>A tuple indicating upload success (bool) and an error message (string), if any.</returns>
public async Task<(bool Success, string Error)> UploadFile(string filePath, string serverPath)
{
Func<string, (bool Success, string Error)> error = (errorMessage) =>
{
logger?.WLog(errorMessage);
return (false, errorMessage);
};
try
{
if (File.Exists(filePath) == false)
return error($"File does not exist: '{filePath}");
if(serverPath.Length > 2 && serverPath[1] != ':')
serverPath = serverPath.Replace("\\", "/");
string url = serverUrl;
if (url.EndsWith("/") == false)
url += "/";
url += "api/file-server";
url += "?path=" + HttpUtility.UrlEncode(serverPath);
logger.ILog("Uploading file to URL: " + url);
await using var fileStream = FileOpenHelper.OpenRead_NoLocks(filePath);
var content = new StreamContent(fileStream);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Add("x-executor", executorUid.ToString());
request.Content = content;
var response = await _client.SendAsync(request);
string body = await response.Content.ReadAsStringAsync();
if(string.IsNullOrWhiteSpace(body) == false)
logger.ILog("Response from server:\n" + body);
if (response.IsSuccessStatusCode == false)
return error($"Upload failed with status code: {response.StatusCode}");
return (true, string.Empty);
}
catch (Exception ex)
{
return error($"An error occurred during upload: {ex.Message}");
}
}
/// <summary>
/// Calculates the SHA256 hash asynchronously for the file located at the specified file path.
/// </summary>
/// <param name="filePath">The path of the file for which the hash needs to be calculated.</param>
/// <returns>The computed SHA256 hash of the file as a byte array.</returns>
private static async Task<byte[]> CalculateFileHash(string filePath)
{
await using var stream = FileOpenHelper.OpenRead_NoLocks(filePath);
return await SHA256.Create().ComputeHashAsync(stream);
}
/// <summary>
/// Deletes a remote path
/// </summary>
/// <param name="path">the path to delete</param>
/// <param name="ifEmpty">if the path is a directory, only delete if its empty, for files this is ignored</param>
/// <param name="includePatterns">
/// the patterns to include for files to determine if the directory is empty
/// eg [mkv, avi, mpg, etc] will treat the directory as empty if none of those files are found
/// </param>
/// <returns>true if successful, otherwise false</returns>
public async Task<(bool Success, string Error)> DeleteRemote(string path, bool ifEmpty, string[] includePatterns)
{
Func<string, (bool Success, string Error)> error = (errorMessage) =>
{
logger?.WLog(errorMessage);
return (false, errorMessage);
};
try
{
string url = serverUrl;
if (url.EndsWith("/") == false)
url += "/";
url += "api/file-server/delete";
string json = JsonSerializer.Serialize(new
{
Path = path,
IfEmpty = ifEmpty,
IncludePatterns = includePatterns
});
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Add("x-executor", executorUid.ToString());
request.Content = new StringContent(json, Encoding.UTF8, "application/json");;
var response = await _client.SendAsync(request);
string body = await response.Content.ReadAsStringAsync();
if(string.IsNullOrWhiteSpace(body) == false)
logger?.ILog(body);
if (response.IsSuccessStatusCode == false)
return error((int)response.StatusCode == 503
? "Failed to delete on server"
: $"Failed to delete with status code: {response.StatusCode}");
return (true, string.Empty);
}
catch (Exception ex)
{
return error($"An error occurred while attempting to delete: {ex.Message}");
}
}
}