-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkUtils.cs
More file actions
280 lines (239 loc) · 10.6 KB
/
Copy pathNetworkUtils.cs
File metadata and controls
280 lines (239 loc) · 10.6 KB
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
using System.Collections.Generic;
using System.Linq;
using nyoka_Client;
using Newtonsoft.Json;
using System.IO;
using static nyoka_Client.Constants;
namespace nyoka_Client
{
public static class NetworkUtils
{
public class NetworkUtilsException : System.Exception
{
public NetworkUtilsException(string mssg)
: base(mssg)
{
}
}
public static bool remoteServerConfigFileExists()
{
return File.Exists(Constants.remoteServerConfigFileName);
}
private static string baseServerUrl(string prefix)
{
if (remoteServerConfigFileExists())
{
return unsafeGetRemoteServerConfigString(prefix);
}
else
{
return "http://localhost:5000";
}
}
public static string unsafeGetRemoteServerConfigString(string prefix)
{
NyokaRemoteInfo nyremote = JsonConvert.DeserializeObject<NyokaRemoteInfo>(File.ReadAllText(remoteServerConfigFileName));
if (prefix=="-s" || prefix=="--zementisserver")
{
return nyremote.ZementisServer;
}
else if (prefix=="-m" || prefix=="--zementismodeler")
{
return nyremote.ZementisModeler;
}
else
{
return nyremote.RepositoryServer;
}
}
private static string getApiUrl(string prefix) => $"{baseServerUrl(prefix)}/api/getresources";
private static string postApiUrl(string prefix) => $"{baseServerUrl(prefix)}/api/postresources";
private static string resourceUrlSection(ResourceType resourceType)
{
if (resourceType == ResourceType.Code) return "code";
if (resourceType == ResourceType.Data) return "data";
if (resourceType == ResourceType.Model) return "models";
throw new NetworkUtilsException("Could not form request to server");
}
private static string resourceFileUrl(string prefix,ResourceType resourceType, string resourceName, string version)
{
return $"{getApiUrl(prefix)}/{resourceUrlSection(resourceType)}/{resourceName}/versions/{version}/file";
}
private static string resourceVersionsUrl(string prefix,ResourceType resourceType, string resourceName)
{
return $"{getApiUrl(prefix)}/{resourceUrlSection(resourceType)}/{resourceName}/versions";
}
private static string resourceDependenciesUrl(string prefix,ResourceType resourceType, string resourceName, string version)
{
return $"{getApiUrl(prefix)}/{resourceUrlSection(resourceType)}/{resourceName}/versions/{version}/dependencies";
}
private static string availableResourcesUrl(string prefix, ResourceType resourceType)
{
return $"{getApiUrl(prefix)}/{resourceUrlSection(resourceType)}";
}
private static string resourcePostUrl(string prefix,ResourceType resourceType, string resourceName, string version)
{
return $"{postApiUrl(prefix)}/{resourceUrlSection(resourceType)}/{resourceName}/versions/{version}/post";
}
private static readonly System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
public static async System.Threading.Tasks.Task downloadResource(
string prefix,
ResourceType resourceType,
string resourceName,
string version,
System.IO.Stream resultStream)
{
long totalFileSize;
try
{
totalFileSize = getResourceVersions(prefix,resourceType, resourceName).versions[version].byteCount;
}
catch (System.Exception)
{
throw new NetworkUtilsException(
$"Could not find {resourceType.ToString().ToLower()} resource {resourceName} at version {version} on server"
);
}
int bufferSize = System.Math.Max(1, System.Math.Min((int)(totalFileSize/100.0), 10000000));
string url = resourceFileUrl(prefix,resourceType, resourceName, version);
try
{
using (var contentStream = await client.GetStreamAsync(url))
{
byte[] buffer = new byte[bufferSize];
bool doneReadingContent = false;
long totalBytesRead = 0;
// @TODO add cancellation?
do
{
int bytesRead = contentStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
doneReadingContent = true;
}
totalBytesRead += bytesRead;
await resultStream.WriteAsync(buffer, 0, bytesRead);
int percentDone = totalFileSize == 0 ? 100 : (int)(100 * (double)totalBytesRead / (double)totalFileSize);
Logger.writeBottomLineOverwriteExisting($"Download {resourceName}: {percentDone}%");
}
while(!doneReadingContent);
Logger.logLine("");
}
}
catch (System.Exception)
{
throw new NetworkUtilsException(
$"Unable to get file for {resourceType} resource {resourceName}"
);
}
}
public static ResourceVersionsInfoContainer getResourceVersions(string prefix,ResourceType resourceType, string resourceName)
{
string url = resourceVersionsUrl(prefix,resourceType, resourceName);
string serializedInfo;
try
{
serializedInfo = client.GetStringAsync(url).Result;
}
catch (System.Exception)
{
throw new NetworkUtilsException(
$"Unable to get list of versions of {resourceType} resource {resourceName} from server"
);
}
try
{
ResourceVersionsInfoContainer versionsInfo = ResourceVersionsInfoContainer.deserialize(serializedInfo);
return versionsInfo;
}
catch (System.Exception)
{
throw new NetworkUtilsException(
$"Unable to process server response to request for " +
$"list of versions of {resourceType} resource {resourceName}"
);
}
}
public static ResourceDependencyInfoContainer getResourceDependencies(string prefix,ResourceType resourceType, string resourceName, string version)
{
string url = resourceDependenciesUrl(prefix, resourceType, resourceName, version);
string serializedInfo;
try
{
serializedInfo = client.GetStringAsync(url).Result;
}
catch (System.Exception)
{
throw new NetworkUtilsException("Unable to get list of package dependencies from server");
}
try
{
ResourceDependencyInfoContainer dependencies = ResourceDependencyInfoContainer.deserialize(serializedInfo);
return dependencies;
}
catch (System.Exception)
{
throw new NetworkUtilsException("Unable to process server response to request for list of dependencies");
}
}
public static AvailableResourcesInfoContainer getAvailableResources(string prefix, ResourceType resourceType)
{
string url = availableResourcesUrl(prefix , resourceType);
string serialized;
try
{
serialized = client.GetStringAsync(url).Result;
}
catch (System.Exception)
{
throw new NetworkUtilsException("Unable to get list of available resources from server");
}
try
{
AvailableResourcesInfoContainer resources = AvailableResourcesInfoContainer.deserialize(serialized);
return resources;
}
catch (System.Exception)
{
throw new NetworkUtilsException("Unable to process server response to available resources request");
}
}
public static void publishResource(
string prefix,
System.IO.FileStream fileStream,
ResourceType resourceType,
string resourceName,
string version,
PublishDepsInfoContainer publishDepsInfo)
{
System.Collections.Specialized.NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryString["deps"] = publishDepsInfo.serialize();
string url = resourcePostUrl(prefix,resourceType, resourceName, version) + "?" + queryString.ToString();
try
{
using (var fileContent = new System.Net.Http.StreamContent(fileStream))
{
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
{
Name = $"files[{resourceName}]",
FileName = resourceName
};
fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
System.Net.Http.HttpResponseMessage statusResult = client.PostAsync(url, fileContent).Result;
if (!statusResult.IsSuccessStatusCode)
{
throw new NetworkUtilsException("Unable to publish: HTTP Error: " + statusResult.StatusCode.ToString());
}
}
}
catch (NetworkUtilsException ex)
{
throw ex;
}
catch (System.Exception)
{
throw new NetworkUtilsException($"Unable to publish {resourceType} resource {resourceName} to server");
}
}
}
}