TaskRunner/TaskRunner/ServerAPI.cs

73 lines
2.3 KiB
C#

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<TaskDTO> GetTask()
{
var resp = await client.GetAsync("/Task");
if (!resp.IsSuccessStatusCode)
{
throw new FailedToGetTaskException();
}
return JsonConvert.DeserializeObject<TaskDTO>(await resp.Content.ReadAsStringAsync());
}
public async Task<StreamDTO> GetStream(string VideoUuid, int StreamId)
{
var resp = await client.GetAsync($"/Videos/{VideoUuid}/Streams/{StreamId}");
if (!resp.IsSuccessStatusCode)
{
throw new FailedToGetStreamException();
}
return JsonConvert.DeserializeObject<StreamDTO>(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<string> 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;
}
}
}