This repository has been archived by the owner on Nov 27, 2023. It is now read-only.
/
LoadImageViewModel.cs
199 lines (161 loc) · 7.62 KB
/
LoadImageViewModel.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Windows.Input;
using AsyncAwaitBestPractices;
using AsyncAwaitBestPractices.MVVM;
using SaveImageToDatabaseSampleApp.Shared;
using Xamarin.Forms;
namespace SaveImageToDatabaseSampleApp
{
public class LoadImageViewModel : BaseViewModel
{
readonly WeakEventManager<string> _imageDownloadFailedEventManager = new();
readonly Lazy<HttpClient> _clientHolder = new(CreateHttpClient);
bool _isImageDownloading, _isImageVisible, _isLoadImageButtonEnabled;
string _imageUrlEntryText = UrlConstants.ImageUrl;
string _downloadImageButtonText = string.Empty;
ImageSource? _downloadedImageSource;
public LoadImageViewModel()
{
LoadImageButtonCommand = new AsyncCommand(() => ExecuteLoadImageButtonCommand(DownloadImageButtonText, ImageUrlEntryText));
InitializeViewModelCommand = new AsyncCommand(ExecuteInitializeViewModelCommand);
ClearImageButtonCommand = new Command(ExecuteClearImageButtonCommand);
ExecuteInitializeViewModelCommand().SafeFireAndForget();
}
public event EventHandler<string> ImageDownloadFailed
{
add => _imageDownloadFailedEventManager.AddEventHandler(value);
remove => _imageDownloadFailedEventManager.RemoveEventHandler(value);
}
public ICommand LoadImageButtonCommand { get; }
public ICommand InitializeViewModelCommand { get; }
public ICommand ClearImageButtonCommand { get; }
public bool IsImageDownloading
{
get => _isImageDownloading;
set => SetProperty(ref _isImageDownloading, value);
}
public bool AreImageAndClearButtonVisible
{
get => _isImageVisible;
set => SetProperty(ref _isImageVisible, value);
}
public string ImageUrlEntryText
{
get => _imageUrlEntryText;
set => SetProperty(ref _imageUrlEntryText, value, async () => await UpdateDownloadButtonText(ImageUrlEntryText).ConfigureAwait(false));
}
public ImageSource? DownloadedImageSource
{
get => _downloadedImageSource;
set => SetProperty(ref _downloadedImageSource, value);
}
public string DownloadImageButtonText
{
get => _downloadImageButtonText;
set => SetProperty(ref _downloadImageButtonText, value);
}
public bool IsLoadImageButtonEnabled
{
get => _isLoadImageButtonEnabled;
set => SetProperty(ref _isLoadImageButtonEnabled, value);
}
HttpClient Client => _clientHolder.Value;
IReadOnlyList<DownloadedImageModel> DownloadedImageModelList { get; set; } = Array.Empty<DownloadedImageModel>();
static HttpClient CreateHttpClient()
{
HttpClient client = Device.RuntimePlatform switch
{
Device.iOS => new HttpClient(),
Device.Android => new HttpClient(),
_ => new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip })
};
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
return client;
}
Task ExecuteInitializeViewModelCommand() => UpdateDownloadButtonText(ImageUrlEntryText);
Task ExecuteLoadImageButtonCommand(string downloadImageButtonText, string imageUrlEntryText) => downloadImageButtonText switch
{
LoadImageButtonTextConstants.LoadImageFromDatabaseButtonText => LoadImageFromDatabaseAsync(imageUrlEntryText),
_ => DownloadImage(imageUrlEntryText),
};
void ExecuteClearImageButtonCommand()
{
AnalyticsServices.Track(AnalyticsConstants.ClearButtonTapped);
AreImageAndClearButtonVisible = false;
}
async Task UpdateDownloadButtonText(string imageUrlEntryText)
{
await RefreshDownloadedImageModelList().ConfigureAwait(false);
if (IsUrInDatabase(imageUrlEntryText))
DownloadImageButtonText = LoadImageButtonTextConstants.LoadImageFromDatabaseButtonText;
else
DownloadImageButtonText = LoadImageButtonTextConstants.DownloadImageFromUrlButtonText;
IsLoadImageButtonEnabled = true;
}
async Task LoadImageFromDatabaseAsync(string imageUrl)
{
AnalyticsServices.Track(AnalyticsConstants.LoadImageFromDatabase, new Dictionary<string, string>
{
{ AnalyticsConstants.ImageUrl, imageUrl }
});
var downloadedImageModel = await DownloadedImageModelDatabase.GetDownloadedImageAsync(imageUrl).ConfigureAwait(false);
DownloadedImageSource = downloadedImageModel.DownloadedImageAsImageStream;
AreImageAndClearButtonVisible = true;
}
async Task DownloadImage(string imageUrl)
{
if (!imageUrl.Trim().StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
OnImageDownloadFailed("URL must use https");
return;
}
SetIsImageDownloading(true);
try
{
using var httpResponse = await Client.GetAsync(imageUrl).ConfigureAwait(false);
if (httpResponse.StatusCode is HttpStatusCode.OK)
{
var downloadedImage = await httpResponse.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
var downloadedImageModel = new DownloadedImageModel
{
ImageUrl = imageUrl,
DownloadedImageBlob = downloadedImage
};
await DownloadedImageModelDatabase.SaveDownloadedImage(downloadedImageModel).ConfigureAwait(false);
DownloadedImageSource = downloadedImageModel.DownloadedImageAsImageStream;
AreImageAndClearButtonVisible = true;
AnalyticsServices.Track(AnalyticsConstants.DownloadImage, AnalyticsConstants.ImageDownloadSuccessful, imageUrl);
}
else
{
AnalyticsServices.Track(AnalyticsConstants.DownloadImage, AnalyticsConstants.ImageDownloadFailed, imageUrl);
OnImageDownloadFailed("Invalid Url");
}
}
catch (Exception e)
{
AnalyticsServices.Track(AnalyticsConstants.DownloadImage, AnalyticsConstants.ImageDownloadFailed, imageUrl);
OnImageDownloadFailed(e.Message);
}
finally
{
SetIsImageDownloading(false);
await UpdateDownloadButtonText(imageUrl).ConfigureAwait(false);
}
}
void SetIsImageDownloading(bool isImageDownloading)
{
IsImageDownloading = isImageDownloading;
IsLoadImageButtonEnabled = !isImageDownloading;
}
bool IsUrInDatabase(string url) => DownloadedImageModelList.Any(x => x.ImageUrl.Equals(url, StringComparison.OrdinalIgnoreCase));
async Task RefreshDownloadedImageModelList() => DownloadedImageModelList = await DownloadedImageModelDatabase.GetAllDownloadedImagesAsync().ConfigureAwait(false);
void OnImageDownloadFailed(string failureMessage) => _imageDownloadFailedEventManager.RaiseEvent(this, failureMessage, nameof(ImageDownloadFailed));
}
}