bitwarden-android/src/App/Services/SiteService.cs

72 lines
2.5 KiB
C#
Raw Normal View History

2016-05-02 09:52:09 +03:00
using System;
using System.Collections.Generic;
using System.Linq;
2016-05-03 09:08:50 +03:00
using System.Net.Http;
using System.Text;
2016-05-02 09:52:09 +03:00
using System.Threading.Tasks;
using Bit.App.Abstractions;
using Bit.App.Models;
2016-05-03 09:08:50 +03:00
using Bit.App.Models.Api;
2016-05-02 09:52:09 +03:00
using Bit.App.Models.Data;
2016-05-03 09:08:50 +03:00
using Newtonsoft.Json;
2016-05-02 09:52:09 +03:00
namespace Bit.App.Services
{
2016-05-03 09:08:50 +03:00
public class SiteService : Repository<SiteData, string>, ISiteService
2016-05-02 09:52:09 +03:00
{
2016-05-03 00:50:16 +03:00
private readonly IAuthService _authService;
2016-05-03 09:08:50 +03:00
private readonly IApiService _apiService;
2016-05-02 09:52:09 +03:00
2016-05-03 00:50:16 +03:00
public SiteService(
ISqlService sqlService,
IAuthService authService,
2016-05-03 09:08:50 +03:00
IApiService apiService)
2016-05-03 00:50:16 +03:00
: base(sqlService)
2016-05-02 09:52:09 +03:00
{
2016-05-03 00:50:16 +03:00
_authService = authService;
2016-05-03 09:08:50 +03:00
_apiService = apiService;
2016-05-03 00:50:16 +03:00
}
public new Task<IEnumerable<Site>> GetAllAsync()
{
var data = Connection.Table<SiteData>().Where(f => f.UserId == _authService.UserId).Cast<SiteData>();
return Task.FromResult(data.Select(s => new Site(s)));
2016-05-02 09:52:09 +03:00
}
2016-05-03 09:08:50 +03:00
public async Task<ApiResult<SiteResponse>> SaveAsync(Site site)
2016-05-02 09:52:09 +03:00
{
2016-05-03 09:08:50 +03:00
var request = new SiteRequest(site);
var requestContent = JsonConvert.SerializeObject(request);
var requestMessage = new HttpRequestMessage
{
Method = site.Id == null ? HttpMethod.Post : HttpMethod.Put,
RequestUri = new Uri(_apiService.Client.BaseAddress, site.Id == null ? "/sites" : string.Concat("/folders/", site.Id)),
Content = new StringContent(requestContent, Encoding.UTF8, "application/json")
};
requestMessage.Headers.Add("Authorization", string.Concat("Bearer ", _authService.Token));
2016-05-02 09:52:09 +03:00
2016-05-03 09:08:50 +03:00
var response = await _apiService.Client.SendAsync(requestMessage);
if(!response.IsSuccessStatusCode)
{
2016-05-03 09:08:50 +03:00
return await _apiService.HandleErrorAsync<SiteResponse>(response);
}
2016-05-03 09:08:50 +03:00
var responseContent = await response.Content.ReadAsStringAsync();
var responseObj = JsonConvert.DeserializeObject<SiteResponse>(responseContent);
var data = new SiteData(responseObj, _authService.UserId);
if(site.Id == null)
2016-05-02 09:52:09 +03:00
{
await CreateAsync(data);
2016-05-03 09:08:50 +03:00
site.Id = responseObj.Id;
2016-05-02 09:52:09 +03:00
}
else
{
await ReplaceAsync(data);
}
2016-05-03 09:08:50 +03:00
return ApiResult<SiteResponse>.Success(responseObj, response.StatusCode);
2016-05-02 09:52:09 +03:00
}
}
}