This repository has been archived by the owner on Nov 17, 2017. It is now read-only.
/
ExplorerViewModel.cs
567 lines (442 loc) · 17.7 KB
/
ExplorerViewModel.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Cimbalino.Phone.Toolkit.Extensions;
using Cimbalino.Phone.Toolkit.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Threading;
using PedroLamas.GDrive.Model;
using PedroLamas.GDrive.Service;
namespace PedroLamas.GDrive.ViewModel
{
public class ExplorerViewModel : ViewModelBase
{
private const string GoogleDriveFilesListFields = "etag,items(description,downloadUrl,fileSize,id,thumbnailLink,labels,mimeType,modifiedDate,title),nextPageToken";
private const string GoogleDriveFileFields = "description,fileSize,id,labels,mimeType,modifiedDate,title";
private readonly IMainModel _mainModel;
private readonly IGoogleDriveService _googleDriveService;
private readonly INavigationService _navigationService;
private readonly IMessageBoxService _messageBoxService;
private readonly ISystemTrayService _systemTrayService;
private readonly IPhotoChooserService _photoChooserService;
private int _pivotSelectedIndex;
private bool _isSelectionEnabled;
private CancellationTokenSource _cancellationTokenSource;
#region Properties
public string AccountName
{
get
{
return _mainModel.CurrentAccount.Name.ToUpperInvariant();
}
}
public string CurrentPath
{
get
{
return _mainModel.CurrentPath;
}
}
public ObservableCollection<GoogleFileViewModel> Files { get; private set; }
public ObservableCollection<GoogleFileViewModel> PictureFiles { get; private set; }
public int PivotSelectedIndex
{
get
{
return _pivotSelectedIndex;
}
set
{
if (_pivotSelectedIndex == value)
return;
_pivotSelectedIndex = value;
RaisePropertyChanged(() => PivotSelectedIndex);
}
}
public bool IsSelectionEnabled
{
get
{
return _isSelectionEnabled;
}
set
{
if (_isSelectionEnabled == value)
return;
_isSelectionEnabled = value;
RaisePropertyChanged(() => IsSelectionEnabled);
RaisePropertyChanged(() => SelectedApplicationBarIndex);
}
}
public int SelectedApplicationBarIndex
{
get
{
return _isSelectionEnabled ? 1 : 0;
}
}
public RelayCommand<GoogleFileViewModel> OpenFileCommand { get; private set; }
public RelayCommand<GoogleFileViewModel> ChangeStaredStatusCommand { get; private set; }
public RelayCommand AddFileCommand { get; private set; }
public RelayCommand EnableSelectionCommand { get; private set; }
public RelayCommand RefreshFilesCommand { get; private set; }
public RelayCommand<IList> DeleteFilesCommand { get; private set; }
public RelayCommand CreateNewFolderCommand { get; private set; }
public RelayCommand<GoogleFileViewModel> RenameFileCommand { get; private set; }
public RelayCommand<GoogleFileViewModel> DeleteFileCommand { get; private set; }
public RelayCommand ShowAboutCommand { get; private set; }
public RelayCommand PageLoadedCommand { get; private set; }
public RelayCommand<CancelEventArgs> BackKeyPressCommand { get; private set; }
public bool IsBusy
{
get
{
return _systemTrayService.IsBusy;
}
}
#endregion
public ExplorerViewModel(IMainModel mainModel, IGoogleDriveService googleDriveService, INavigationService navigationService, IMessageBoxService messageBoxService, ISystemTrayService systemTrayService, IPhotoChooserService photoChooserService)
{
_mainModel = mainModel;
_googleDriveService = googleDriveService;
_navigationService = navigationService;
_messageBoxService = messageBoxService;
_systemTrayService = systemTrayService;
_photoChooserService = photoChooserService;
Files = new ObservableCollection<GoogleFileViewModel>();
PictureFiles = new ObservableCollection<GoogleFileViewModel>();
OpenFileCommand = new RelayCommand<GoogleFileViewModel>(file =>
{
if (IsSelectionEnabled)
{
return;
}
OpenFile(file);
});
ChangeStaredStatusCommand = new RelayCommand<GoogleFileViewModel>(file =>
{
if (IsSelectionEnabled)
{
return;
}
ChangeStaredStatus(file);
});
AddFileCommand = new RelayCommand(UploadFile);
EnableSelectionCommand = new RelayCommand(() =>
{
if (IsBusy)
{
return;
}
IsSelectionEnabled = true;
});
RefreshFilesCommand = new RelayCommand(RefreshFiles);
DeleteFilesCommand = new RelayCommand<IList>(files =>
{
_messageBoxService.Show("You are about to delete the selected files. Do you wish to proceed?", "Delete files?", new[] { "delete", "cancel" }, button =>
{
if (button != 0)
return;
var filesArray = files
.Cast<GoogleFileViewModel>()
.ToArray();
IsSelectionEnabled = false;
DeleteFiles(filesArray);
});
});
CreateNewFolderCommand = new RelayCommand(CreateNewFolder);
RenameFileCommand = new RelayCommand<GoogleFileViewModel>(RenameFile);
DeleteFileCommand = new RelayCommand<GoogleFileViewModel>(file =>
{
_messageBoxService.Show(string.Format("You are about to delete '{0}'. Do you wish to proceed?", file.Title), "Delete file?", new[] { "delete", "cancel" }, button =>
{
if (button != 0)
return;
DeleteFile(file);
});
});
ShowAboutCommand = new RelayCommand(() =>
{
_navigationService.NavigateTo("/View/AboutPage.xaml");
});
PageLoadedCommand = new RelayCommand(ExecuteInitialLoad);
BackKeyPressCommand = new RelayCommand<CancelEventArgs>(e =>
{
GoogleDriveFile item;
if (PivotSelectedIndex == 1)
{
PivotSelectedIndex = 0;
e.Cancel = true;
}
else if (IsSelectionEnabled)
{
IsSelectionEnabled = false;
e.Cancel = true;
}
else if (_mainModel.TryPop(out item))
{
AbortCurrentCall();
RaisePropertyChanged(() => CurrentPath);
RefreshFiles();
e.Cancel = true;
}
else
{
AbortCurrentCall(true);
Files.Clear();
PictureFiles.Clear();
}
});
MessengerInstance.Register<RefreshFilesMessage>(this, message =>
{
DispatcherHelper.RunAsync(RefreshFiles);
});
}
private async void ExecuteInitialLoad()
{
if (!_mainModel.ExecuteInitialLoad)
{
return;
}
_mainModel.ExecuteInitialLoad = false;
AbortCurrentCall();
try
{
await _mainModel.CheckToken(_cancellationTokenSource.Token);
_systemTrayService.SetProgressIndicator("Reading drive info...");
var about = await _googleDriveService.About(_mainModel.CurrentAccount.AuthToken, new GoogleDriveAboutRequest()
{
ETag = _mainModel.CurrentAccount.Info != null ? _mainModel.CurrentAccount.Info.ETag : null
}, _cancellationTokenSource.Token);
if (about != null)
{
_mainModel.CurrentAccount.Info = about;
_mainModel.Save();
}
await RefreshFilesAsync();
}
catch (TaskCanceledException)
{
_systemTrayService.HideProgressIndicator();
}
catch (Exception)
{
_systemTrayService.HideProgressIndicator();
_messageBoxService.Show("Unable to get the drive information!", "Error");
}
}
private void OpenFile(GoogleFileViewModel fileViewModel)
{
if (fileViewModel.IsFolder)
{
_mainModel.Push(fileViewModel.FileModel);
RaisePropertyChanged(() => CurrentPath);
RefreshFiles();
}
else
{
_mainModel.SelectedFile = fileViewModel.FileModel;
_navigationService.NavigateTo("/View/ViewFilePage.xaml");
}
}
private async void ChangeStaredStatus(GoogleFileViewModel fileViewModel)
{
if (IsBusy)
{
return;
}
AbortCurrentCall();
try
{
await _mainModel.CheckToken(_cancellationTokenSource.Token);
_systemTrayService.SetProgressIndicator("Changing file star state...");
var currentStaredtatus = fileViewModel.FileModel.Labels.Starred;
var fileModel = await _googleDriveService.FilesUpdate(_mainModel.CurrentAccount.AuthToken, fileViewModel.Id, new GoogleDriveFilesUpdateRequest()
{
File = new GoogleDriveFile()
{
Labels = new GoogleDriveLabels()
{
Starred = !currentStaredtatus.GetValueOrDefault()
}
},
Fields = GoogleDriveFileFields
}, _cancellationTokenSource.Token);
fileViewModel.FileModel = fileModel;
_systemTrayService.HideProgressIndicator();
}
catch (TaskCanceledException)
{
_systemTrayService.HideProgressIndicator();
}
catch (Exception)
{
_systemTrayService.HideProgressIndicator();
_messageBoxService.Show("Unable to change the file star state!", "Error");
}
}
private void UploadFile()
{
AbortCurrentCall();
_photoChooserService.Show(true, result =>
{
if (result.TaskResult != Microsoft.Phone.Tasks.TaskResult.OK)
return;
DispatcherHelper.RunAsync(async () =>
{
try
{
await _mainModel.CheckToken(_cancellationTokenSource.Token);
_systemTrayService.SetProgressIndicator("Uploading the file...");
var fileModel = await _googleDriveService.FilesInsert(_mainModel.CurrentAccount.AuthToken, new GoogleDriveFilesInsertRequest()
{
Filename = System.IO.Path.GetFileName(result.OriginalFileName),
FileContent = result.ChosenPhoto.ToArray(),
FolderId = _mainModel.CurrentFolderId,
Fields = GoogleDriveFileFields
}, _cancellationTokenSource.Token);
var googleFileViewModel = new GoogleFileViewModel(fileModel);
Files.Add(googleFileViewModel);
if (!string.IsNullOrEmpty(googleFileViewModel.ThumbnailLink))
{
PictureFiles.Add(googleFileViewModel);
}
_systemTrayService.HideProgressIndicator();
}
catch (TaskCanceledException)
{
_systemTrayService.HideProgressIndicator();
}
catch (Exception)
{
_systemTrayService.HideProgressIndicator();
_messageBoxService.Show("Unable to upload the file!", "Error");
}
});
});
}
private async void RefreshFiles()
{
await RefreshFilesAsync();
}
private void CreateNewFolder()
{
AbortCurrentCall();
_navigationService.NavigateTo("/View/NewFolderPage.xaml");
}
private void RenameFile(GoogleFileViewModel fileViewModel)
{
_mainModel.SelectedFile = fileViewModel.FileModel;
_navigationService.NavigateTo("/View/RenameFilePage.xaml");
}
private async void DeleteFile(GoogleFileViewModel fileViewModel)
{
AbortCurrentCall();
await DeleteFileAsync(fileViewModel);
_systemTrayService.HideProgressIndicator();
}
private async void DeleteFiles(IEnumerable<GoogleFileViewModel> filesToDelete)
{
AbortCurrentCall();
foreach (var fileViewModel in filesToDelete)
{
if (!await DeleteFileAsync(fileViewModel))
{
break;
}
}
_systemTrayService.HideProgressIndicator();
}
private async Task RefreshFilesAsync()
{
AbortCurrentCall();
try
{
var currentFolderId = _mainModel.CurrentFolderId;
await _mainModel.CheckToken(_cancellationTokenSource.Token);
_systemTrayService.SetProgressIndicator("Refreshing the file list...");
Files.Clear();
PictureFiles.Clear();
string pageToken = null;
while (true)
{
var filesListResponse = await _googleDriveService.FilesList(_mainModel.CurrentAccount.AuthToken, new GoogleDriveFilesListRequest()
{
Query = "trashed=false and '{0}' in parents".FormatWith(currentFolderId),
Fields = GoogleDriveFilesListFields,
PageToken = pageToken
}, _cancellationTokenSource.Token);
if (filesListResponse.Items != null)
{
foreach (var item in filesListResponse.Items)
{
var googleFileViewModel = new GoogleFileViewModel(item);
Files.Add(googleFileViewModel);
if (item != null && !string.IsNullOrEmpty(item.ThumbnailLink))
{
PictureFiles.Add(googleFileViewModel);
}
}
}
pageToken = filesListResponse.NextPageToken;
if (string.IsNullOrEmpty(pageToken))
{
_systemTrayService.HideProgressIndicator();
return;
}
}
}
catch (TaskCanceledException)
{
_systemTrayService.HideProgressIndicator();
}
catch (Exception)
{
_systemTrayService.HideProgressIndicator();
_messageBoxService.Show("Unable to update the file list!", "Error");
}
}
private async Task<bool> DeleteFileAsync(GoogleFileViewModel fileViewModel)
{
try
{
await _mainModel.CheckToken(_cancellationTokenSource.Token);
_systemTrayService.SetProgressIndicator(string.Format("Deleting: {0}...", fileViewModel.Title));
await _googleDriveService.FilesDelete(_mainModel.CurrentAccount.AuthToken, fileViewModel.Id, _cancellationTokenSource.Token);
lock (Files)
{
if (Files.Contains(fileViewModel))
{
Files.Remove(fileViewModel);
}
}
return true;
}
catch
{
_systemTrayService.HideProgressIndicator();
_messageBoxService.Show(string.Format("Unable to delete '{0}'!", fileViewModel.Title), "Error");
}
return false;
}
private void AbortCurrentCall(bool hideSystemTray = false)
{
if (hideSystemTray)
{
_systemTrayService.HideProgressIndicator();
}
if (_cancellationTokenSource != null)
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
}
_cancellationTokenSource = new CancellationTokenSource();
}
}
}