Fix #2121, manual changes to the API Key were not passed to the appropriate PithosMon...
[pithos-ms-client] / trunk / Pithos.Client.WPF / Preferences / AddAccountViewModel.cs
1 #region
2 /* -----------------------------------------------------------------------
3  * <copyright file="AddAccountViewModel.cs" company="GRNet">
4  * 
5  * Copyright 2011-2012 GRNET S.A. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or
8  * without modification, are permitted provided that the following
9  * conditions are met:
10  *
11  *   1. Redistributions of source code must retain the above
12  *      copyright notice, this list of conditions and the following
13  *      disclaimer.
14  *
15  *   2. Redistributions in binary form must reproduce the above
16  *      copyright notice, this list of conditions and the following
17  *      disclaimer in the documentation and/or other materials
18  *      provided with the distribution.
19  *
20  *
21  * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  * The views and conclusions contained in the software and
35  * documentation are those of the authors and should not be
36  * interpreted as representing official policies, either expressed
37  * or implied, of GRNET S.A.
38  * </copyright>
39  * -----------------------------------------------------------------------
40  */
41 #endregion
42 using System;
43 using System.Collections.Generic;
44 using System.ComponentModel.Composition;
45 using System.Threading.Tasks;
46 using System.Windows;
47 using System.Windows.Forms;
48 using Pithos.Client.WPF.Properties;
49 using Pithos.Network;
50 using MessageBox = System.Windows.MessageBox;
51 using Screen = Caliburn.Micro.Screen;
52
53 namespace Pithos.Client.WPF.Preferences
54 {
55     [Export(typeof(AddAccountViewModel))]
56     public class AddAccountViewModel:Screen
57     {
58
59         private readonly List<string> _servers;
60
61         public List<string> Servers
62         {
63             get { return _servers; }
64         }
65
66         private bool _isValidServer;
67         public bool IsValidServer
68         {
69             get { return _isValidServer; }
70             set
71             {
72                 _isValidServer = value;
73                 NotifyOfPropertyChange(()=>IsValidServer);
74             }
75         }
76
77
78         private string _currentServer;
79         public string CurrentServer
80         {
81             get { return _currentServer; }
82             set
83             {
84                 if (!Uri.IsWellFormedUriString(value, UriKind.Absolute))
85                 {
86                     IsValidServer = false;
87                     throw new UriFormatException();
88                 }
89                 _currentServer = value;
90                 IsValidServer = true;
91                 HasValidCredentials = false;
92                 IsConfirmed = false;
93                 NotifyOfPropertyChange(()=>CurrentServer);
94             }
95         }
96
97         private string _accountName;
98         public string AccountName
99         {
100             get { return _accountName; }
101             set
102             {
103                 _accountName = value;
104                 NotifyOfPropertyChange(()=>AccountName);
105                 NotifyOfPropertyChange(() => HasCredentials);
106             }
107         }
108
109         private string _token;
110         public string Token
111         {
112             get { return _token; }
113             set
114             {
115                 _token = value;
116                 NotifyOfPropertyChange(()=>Token);
117                 NotifyOfPropertyChange(() => HasCredentials);
118             }
119         }
120
121         private string _accountPath;
122         public string AccountPath
123         {
124             get { return _accountPath; }
125             set
126             {
127                 _accountPath = value;
128                 NotifyOfPropertyChange(() => AccountPath);
129                 NotifyOfPropertyChange(() => HasAccountPath);
130             }
131         }
132
133
134         public bool HasAccountPath
135         {
136             get { return !String.IsNullOrWhiteSpace(AccountPath); }
137         }
138
139         public bool HasCredentials
140         {
141             get { return !(String.IsNullOrWhiteSpace(AccountName) || String.IsNullOrWhiteSpace(Token) ) ; }
142         }
143
144
145         private bool  _isConfirmed;
146
147         public bool IsConfirmed
148         {
149             get { return _isConfirmed; }
150             set
151             {
152                 _isConfirmed = value;
153                 HasValidCredentials = false;
154                 NotifyOfPropertyChange(() => IsConfirmed);
155             }
156         }
157
158
159         private bool _isAccountActive;
160
161         public bool IsAccountActive
162         {
163             get { return _isAccountActive; }
164             set
165             {
166                 _isAccountActive = value;
167                 NotifyOfPropertyChange(() => IsAccountActive);
168             }
169         }
170
171         public void SelectAccount()
172         {
173             using (var dlg = new FolderBrowserDialog{Description=Resources.AddAccountViewModel_SelectAccount_Please_select_a_folder})
174             {
175                 //Ask the user to select a folder
176                 //Note: We need a parent window here, which we retrieve with GetView            
177                 var view = (Window)GetView();
178                 if (DialogResult.OK != dlg.ShowDialog(new Wpf32Window(view)))
179                     return;
180
181                 AccountPath= dlg.SelectedPath;
182             }
183         }
184
185
186         public async void RetrieveCredentials()
187         {
188             SetBusy("Waiting for credentials.", "Please enter your credentials in the Pithos logon page");
189             IsConfirmed = false;
190
191             try
192             {
193                 var credentials = await PithosAccount.RetrieveCredentials(Settings.Default.PithosLoginUrl);
194                 AccountName = credentials.UserName;
195                 Token = credentials.Password;
196
197                 IsConfirmed = true;
198             }
199             catch (PithosException exc)
200             {
201                 ClearBusy();
202                 MessageBox.Show(exc.Message, "Unable to retrieve credentials");
203             }
204             catch (Exception exc)
205             {
206                 IsConfirmed = false;
207                 MessageBox.Show(exc.ToString(), "Error");
208                 throw;
209             }
210             finally
211             {
212                 ClearBusy();
213                 
214                 ((Window) GetView()).Activate();
215             }
216
217         }
218
219         public AddAccountViewModel()
220         {
221             _servers=new List<string>
222                          {
223                              Settings.Default.ProductionServer, 
224                              Settings.Default.DevelopmentServer
225                          };
226             CurrentServer = _servers[0];
227         }
228
229         private bool _hasValidCredentials;
230         public bool HasValidCredentials
231         {
232             get { return _hasValidCredentials; }
233             set
234             {
235                 _hasValidCredentials = value;
236                 NotifyOfPropertyChange(()=>HasValidCredentials);
237             }
238         }
239
240         private string _validationMessage;
241         public string ValidationMessage
242         {
243             get { return _validationMessage; }
244             set
245             {
246                 _validationMessage = value;
247                 NotifyOfPropertyChange(()=>ValidationMessage);
248             }
249         }
250
251         private bool _isWorking;
252         public bool IsWorking
253         {
254             get { return _isWorking; }
255             set
256             {
257                 _isWorking = value;
258                 NotifyOfPropertyChange(()=>IsWorking);
259             }
260         }
261
262         private string _busyTitle;
263         public string BusyTitle
264         {
265             get { return _busyTitle; }
266             set
267             {
268                 _busyTitle = value;
269                 NotifyOfPropertyChange(()=>BusyTitle);
270             }
271         }
272
273         private string _busyDetail;
274         public string BusyDetail
275         {
276             get { return _busyDetail; }
277             set
278             {
279                 _busyDetail = value;
280                 NotifyOfPropertyChange(()=>BusyDetail);
281             }
282         }
283
284         private void SetBusy(string title,string detail)
285         {
286             IsWorking = true;
287             BusyTitle = title;
288             BusyDetail = detail;
289         }
290
291         private void ClearBusy()
292         {
293             IsWorking = false;
294             BusyTitle = "";
295             BusyDetail = "";
296             
297         }
298
299         public async void TestAccount()
300         {
301             try
302             {
303                 SetBusy("Validating Credentials", "");
304                 var client = new CloudFilesClient(AccountName, Token) { AuthenticationUrl = CurrentServer,/*Proxy=Proxy */};                
305                 await TaskEx.Run(() =>
306                                      {
307                                          client.Authenticate();
308                                          return client.ListContainers(AccountName);
309                                      });
310                 HasValidCredentials = true;
311                 ValidationMessage = "Credentials Validated";
312             }
313             catch
314             {
315                 HasValidCredentials = false;
316                 MessageBox.Show("The account is not valid", "Account Error", MessageBoxButton.OK, MessageBoxImage.Stop);
317                 ValidationMessage = "Credentials validation failed";
318             }
319             finally
320             {
321                 ClearBusy();
322             }
323         }
324
325     }
326 }