forked from microsoft/Appsample-Photosharing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUploadViewModel.cs
462 lines (402 loc) · 15.4 KB
/
UploadViewModel.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//-----------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ---------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using PhotoSharingApp.Universal.Commands;
using PhotoSharingApp.Universal.Extensions;
using PhotoSharingApp.Universal.Facades;
using PhotoSharingApp.Universal.Models;
using PhotoSharingApp.Universal.Services;
using PhotoSharingApp.Universal.Telemetry;
using PhotoSharingApp.Universal.Views;
using Windows.Storage;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
namespace PhotoSharingApp.Universal.ViewModels
{
/// <summary>
/// The ViewModel for the upload view.
/// </summary>
public class UploadViewModel : ViewModelBase
{
/// <summary>
/// The authentication enforcement handler.
/// </summary>
private readonly IAuthEnforcementHandler _authEnforcementHandler;
/// <summary>
/// The bitmap image.
/// </summary>
private BitmapImage _bitmapImage;
/// <summary>
/// The category
/// </summary>
private Category _category;
/// <summary>
/// The comment
/// </summary>
private string _comment;
private readonly IDialogService _dialogService;
/// <summary>
/// Specifies the editing mode
/// </summary>
private EditingMode _editingMode;
/// <summary>
/// Specifies if work is in progress
/// </summary>
private bool _isBusy;
/// <summary>
/// The navigation facade
/// </summary>
private readonly INavigationFacade _navigationFacade;
/// <summary>
/// The photo service
/// </summary>
private readonly IPhotoService _photoService;
/// <summary>
/// The telemetry client.
/// </summary>
private readonly TelemetryClient _telemetryClient;
/// <summary>
/// The event handler for handling a successful upload.
/// </summary>
private readonly IUploadFinishedHandler _uploadFinishedHandler;
/// <summary>
/// The writeable bitmap of the photo to upload.
/// </summary>
private WriteableBitmap _writeableBitmap;
/// <summary>
/// Initializes a new instance of the <see cref="UploadViewModel" /> class.
/// </summary>
/// <param name="navigationFacade">The navigation facade.</param>
/// <param name="photoService">The photo service.</param>
/// <param name="authEnforcementHandler">Authentication enforcement handler.</param>
/// <param name="telemetryClient">The telemetry client.</param>
/// <param name="uploadFinishedHandler">The handler that is called when the upload finished.</param>
/// <param name="dialogService">The dialog service.</param>
public UploadViewModel(INavigationFacade navigationFacade, IPhotoService photoService,
IAuthEnforcementHandler authEnforcementHandler, TelemetryClient telemetryClient,
IUploadFinishedHandler uploadFinishedHandler, IDialogService dialogService)
{
_navigationFacade = navigationFacade;
_photoService = photoService;
_authEnforcementHandler = authEnforcementHandler;
_telemetryClient = telemetryClient;
_uploadFinishedHandler = uploadFinishedHandler;
_dialogService = dialogService;
// Initialize commands
UploadCommand = new RelayCommand(OnUpload, () => !IsBusy);
ChooseCategoryCommand = new RelayCommand(OnChooseCategory, () => !IsBusy);
}
/// <summary>
/// Gets or sets the photo as <see cref="BitmapImage" />.
/// </summary>
public BitmapImage BitmapImage
{
get { return _bitmapImage; }
set
{
if (value != _bitmapImage)
{
_bitmapImage = value;
NotifyPropertyChanged(nameof(BitmapImage));
NotifyPropertyChanged(nameof(ImageSource));
}
}
}
/// <summary>
/// Gets or sets the category.
/// </summary>
/// <value>
/// The category.
/// </value>
public Category Category
{
get { return _category; }
set
{
if (value != _category)
{
_category = value;
NotifyPropertyChanged(nameof(Category));
}
}
}
/// <summary>
/// Gets the choose category command.
/// </summary>
public RelayCommand ChooseCategoryCommand { get; }
/// <summary>
/// Gets or sets the comment.
/// </summary>
/// <value>
/// The comment.
/// </value>
public string Comment
{
get { return _comment; }
set
{
if (value != _comment)
{
_comment = value;
NotifyPropertyChanged(nameof(Comment));
}
}
}
/// <summary>
/// Gets the image source that is being displayed
/// in the UI.
/// </summary>
public ImageSource ImageSource
{
get
{
if (WriteableBitmap != null)
{
return WriteableBitmap;
}
return BitmapImage;
}
}
/// <summary>
/// Gets or sets a value indicating whether this instance is busy.
/// </summary>
/// <value>
/// <c>true</c> if this instance is busy; otherwise, <c>false</c>.
/// </value>
public bool IsBusy
{
get { return _isBusy; }
set
{
if (value != _isBusy)
{
_isBusy = value;
NotifyPropertyChanged(nameof(IsBusy));
UploadCommand.RaiseCanExecuteChanged();
ChooseCategoryCommand.RaiseCanExecuteChanged();
}
}
}
/// <summary>
/// Gets or sets the photo.
/// </summary>
public Photo Photo { get; set; }
/// <summary>
/// Gets the upload command.
/// </summary>
/// <value>
/// The upload command.
/// </value>
public RelayCommand UploadCommand { get; }
/// <summary>
/// Gets or sets the photo as <see cref="WriteableBitmap" />.
/// </summary>
public WriteableBitmap WriteableBitmap
{
get { return _writeableBitmap; }
set
{
if (value != _writeableBitmap)
{
_writeableBitmap = value;
NotifyPropertyChanged(nameof(WriteableBitmap));
NotifyPropertyChanged(nameof(ImageSource));
}
}
}
/// <summary>
/// Loads the view model state.
/// </summary>
/// <param name="uploadViewModelEditPhotoArgs">The arguments.</param>
public async Task LoadState(UploadViewModelEditPhotoArgs uploadViewModelEditPhotoArgs)
{
await base.LoadState();
_editingMode = EditingMode.Update;
Category = uploadViewModelEditPhotoArgs.Category;
Photo = uploadViewModelEditPhotoArgs.Photo;
Comment = Photo.Caption;
BitmapImage = new BitmapImage(new Uri(Photo.ImageUrl));
}
/// <summary>
/// Loads the state.
/// </summary>
/// <param name="args">The view model arguments.</param>
public async Task LoadState(UploadViewModelArgs args)
{
await base.LoadState();
_editingMode = EditingMode.New;
Category = args.Category?.ToCategory();
try
{
// The user needs to be signed-in
await _authEnforcementHandler.CheckUserAuthentication();
// When navigating directly from the main window, the user has not
// selected a category yet, so we need to do this now.
if (Category == null)
{
Category = await _navigationFacade.ShowCategoryChooserDialog();
}
// Here is some synchronization issue going on,
// when we first set the Photo which propagates to the UI
// via data binding, and immediately open a ContentDialog via ShowCategoryChooserDialog.
// We would get random component initialization exceptions from XAML
// without any further details. This however is only noticeable when
// the app is launched as share target.
// As a solution, we assign the selected photo after the chooser dialog
// has been awaited.
WriteableBitmap = args.Image;
}
catch (SignInRequiredException)
{
await _dialogService.ShowNotification("AuthenticationRequired_Message", "AuthenticationRequired_Title");
_navigationFacade.GoBack();
}
}
private async void OnChooseCategory()
{
_telemetryClient.TrackEvent(TelemetryEvents.EditCategoryInvoked);
var selectedCategory = await _navigationFacade.ShowCategoryChooserDialog();
if (selectedCategory != null)
{
Category = selectedCategory;
}
}
private async void OnUpload()
{
if (_editingMode == EditingMode.New)
{
await UploadNewPhoto();
}
else
{
await UpdatePhoto();
}
}
private async Task UpdatePhoto()
{
try
{
_telemetryClient.TrackEvent(TelemetryEvents.UpdatePhotoInitiated);
// The user needs to be signed-in
await _authEnforcementHandler.CheckUserAuthentication();
// If the current category is not selected, prompt
// the user to select one.
if (Category == null)
{
Category = await _navigationFacade.ShowCategoryChooserDialog();
// If category is still not selected (User can always cancel),
// we need to cancel the upload.
if (Category == null)
{
throw new CategoryRequiredException();
}
}
IsBusy = true;
Photo.Caption = Comment;
Photo.CategoryId = Category.Id;
await _photoService.UpdatePhoto(Photo);
_navigationFacade.NavigateToPhotoDetailsView(Category.ToCategoryPreview(), Photo);
_telemetryClient.TrackEvent(TelemetryEvents.UpdatePhotoSuccess);
}
catch (CategoryRequiredException)
{
// Swallow exception. User canceled selecting a category.
}
catch (SignInRequiredException)
{
// Swallow exception. User canceled the Sign-in dialog.
}
catch (ServiceException)
{
await _dialogService.ShowNotification("GenericError_Message", "GenericError_Title");
}
finally
{
IsBusy = false;
}
}
/// <summary>
/// Uploads the photo.
/// </summary>
private async Task UploadNewPhoto()
{
try
{
var startTime = DateTime.Now;
_telemetryClient.TrackEvent(TelemetryEvents.UploadPhotoInitiated);
// The user needs to be signed-in
await _authEnforcementHandler.CheckUserAuthentication();
// If the current category is not selected, prompt
// the user to select one.
if (Category == null)
{
Category = await _navigationFacade.ShowCategoryChooserDialog();
// If category is still not selected (User can always cancel),
// we need to cancel the upload.
if (Category == null)
{
throw new CategoryRequiredException();
}
}
IsBusy = true;
var file =
await
ApplicationData.Current.TemporaryFolder.CreateFileAsync("myPhoto.jpg",
CreationCollisionOption.ReplaceExisting);
await WriteableBitmap.SaveToStorageFile(file);
var stream = await file.OpenStreamForReadAsync();
var uploadedPhoto = await _photoService.UploadPhoto(stream, file.Path, Comment, Category.Id);
// Refresh gold balance
AppEnvironment.Instance.CurrentUser = uploadedPhoto.User;
// Telemetry that upload finished successfully
var timeTaken = DateTime.Now - startTime;
_telemetryClient.TrackEvent(TelemetryEvents.UploadPhotoSuccess, null, new Dictionary<string, double>
{
{ TelemetryProperties.TotalTimeToUploadPhoto, timeTaken.TotalMilliseconds }
});
await _uploadFinishedHandler.OnUploadFinished(Category);
}
catch (CategoryRequiredException)
{
// User canceled selecting a category.
}
catch (SignInRequiredException)
{
// User canceled the Sign-in dialog.
}
catch (ServiceException)
{
await _dialogService.ShowNotification("GenericError_Message", "GenericError_Title");
}
finally
{
IsBusy = false;
}
}
}
}