tesses.backup/Tesses.Backup.Client/Class1.cs

75 lines
2.9 KiB
C#

/*
A simple Backup Client / Server
Copyright (C) 2023 Mike Nolan
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Tesses.Backup.Models;
namespace Tesses.Backup
{
public sealed class BackupClient
{
HttpClient clt;
public BackupClient(HttpClient client)
{
clt = client;
}
public BackupClient(Uri url) : this(new HttpClient(){BaseAddress=url})
{
}
public BackupClient(string url) : this(new Uri(url))
{
}
public HttpClient Client {get{return clt;}}
internal async Task<TResponse> MakeJsonPostRequestAsync<TResponse>(string url,object req)
{
StringContent json =new StringContent(JsonConvert.SerializeObject(req),Encoding.UTF8);
var resp=await clt.PostAsync(url,json);
return JsonConvert.DeserializeObject<TResponse>(await resp.Content.ReadAsStringAsync());
}
public async Task<ChangePasswordResponse> ChangePasswordAsync(string username,string oldPassword,string newPassword,string confirmPassword)
{
ChangePasswordRequest request = new ChangePasswordRequest();
request.UserName = username;
request.OldPassword = oldPassword;
request.NewPassword = newPassword;
request.ConfirmNewPassword = confirmPassword;
return await ChangePasswordAsync(request);
}
public async Task<ChangePasswordResponse> ChangePasswordAsync(ChangePasswordRequest request)
{
return await MakeJsonPostRequestAsync<ChangePasswordResponse>("/api/v1/ChangePassword",request);
}
public async Task<BackupSession> LoginAsync(string username,string password)
{
return await LoginAsync(new LoginRequest(){UserName=username,Password=password});
}
public async Task<BackupSession> LoginAsync(LoginRequest request)
{
var loginResp=await MakeJsonPostRequestAsync<LoginResponse>("/api/v1/Login",request);
return new BackupSession(loginResp,this);
}
}
}