using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using TaskRunner.DTOs; using Newtonsoft.Json; using System.IO; namespace TaskRunner { public class TaskRunnerException:Exception { } public class FailedToGetTaskException:TaskRunnerException { } public class FailedToGetStreamException:TaskRunnerException { } public class ServerApi { public Uri serverUri; private readonly HttpClient client = new HttpClient(); public ServerApi(Uri serverUri) { this.serverUri = serverUri; client.BaseAddress = serverUri; } public async Task GetTask() { var resp = await client.GetAsync("/Task"); if (!resp.IsSuccessStatusCode) { throw new FailedToGetTaskException(); } return JsonConvert.DeserializeObject(await resp.Content.ReadAsStringAsync()); } public async Task GetStream(string VideoUuid, int StreamId) { var resp = await client.GetAsync($"/Videos/{VideoUuid}/Streams/{StreamId}"); if (!resp.IsSuccessStatusCode) { throw new FailedToGetStreamException(); } return JsonConvert.DeserializeObject(await resp.Content.ReadAsStringAsync()); } } public class FileStorage { private string baseDir = Path.GetFullPath("files"); public FileStorage() { } public FileStorage(string dir) { baseDir = Path.GetFullPath(dir); } public async Task DownloadFile(Uri uri) { var entity = await (new HttpClient()).GetAsync(uri); if (!entity.IsSuccessStatusCode) { throw new TaskRunnerException(); } var fileName = uri.Segments.Last(); var fullPath = Path.Combine(baseDir, fileName); Console.WriteLine(fileName); Directory.CreateDirectory(baseDir); //File.Create(fullPath); using (var fos = File.OpenWrite(fullPath)) { await entity.Content.CopyToAsync(fos); } return fullPath; } } }