Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / SelectiveSynch / SelectiveSynchViewModel.cs @ 1c9bbe2c

History | View | Annotate | Download (11.8 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="SelectiveSynchViewModel.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.Collections.ObjectModel;
45
using System.Linq;
46
using System.Threading.Tasks;
47
using Caliburn.Micro;
48
using Pithos.Client.WPF.Properties;
49
using Pithos.Client.WPF.Utils;
50
using Pithos.Core;
51
using Pithos.Interfaces;
52
using Pithos.Network;
53

    
54
namespace Pithos.Client.WPF.SelectiveSynch
55
{
56
    class SelectiveSynchViewModel:Screen
57
    {        
58
        private readonly IEventAggregator _events ;
59

    
60

    
61
        public AccountSettings Account { get; set; }
62

    
63
        private readonly ObservableCollection<DirectoryRecord> _rootNodes=new ObservableCollection<DirectoryRecord>();
64
        public ObservableCollection<DirectoryRecord> RootNodes
65
        {
66
            get { return _rootNodes; }
67
        }
68

    
69
        private ObservableCollection<ObjectInfo> _checks;
70
        //private readonly PithosMonitor _monitor;
71
        private bool _isBusy=true;
72
        private readonly string _apiKey;
73

    
74
        public ObservableCollection<ObjectInfo> Checks
75
        {
76
            get { return _checks; }
77
        }
78

    
79
        public void GetChecks()
80
        {
81
            var root = RootNodes[0];            
82
            _checks = new ObservableCollection<ObjectInfo>(
83
                from DirectoryRecord record in root
84
                where record.IsChecked==true
85
                select record.ObjectInfo);
86
            NotifyOfPropertyChange(() => Checks);
87
        }
88

    
89
        public SelectiveSynchViewModel(/*PithosMonitor monitor,*/ IEventAggregator events, AccountSettings account, string apiKey)
90
        {
91
            Account = account;
92
            AccountName = account.AccountName;
93
            DisplayName = String.Format("Selective folder synchronization for {0}",account.AccountName);
94
            //_monitor = monitor;
95
            _events = events;
96
            _apiKey = apiKey;
97
            TaskEx.Run(LoadRootNode);
98
        }
99

    
100
        private void LoadRootNode()
101
        {            
102
            //TODO: Check this
103
            var client = new CloudFilesClient(AccountName,_apiKey){AuthenticationUrl=Account.ServerUrl,UsePithos=true};
104
            client.Authenticate();
105
            
106
            //NEED to get the local folders here as well,
107
            // and combine them with the cloud folders
108

    
109

    
110
            var dirs = from container in client.ListContainers(AccountName)  
111
                       where container.Name != "trash"
112
                       select new DirectoryRecord
113
                                  {
114
                                      DisplayName = container.Name,
115
                                      Uri=new Uri(client.StorageUrl,String.Format(@"{0}/{1}",Account.AccountName, container.Name)),
116
                                      Directories = (from dir in client.ListObjects(AccountName, container.Name)                                                                                                          
117
                                                     select dir).ToTree()
118
                                  };
119
            var ownFolders = dirs.ToList();
120

    
121

    
122

    
123
            var accountNodes=from account in client.ListSharingAccounts()
124
                             select new DirectoryRecord
125
                             {
126
                                DisplayName=account.name,
127
                                Uri=new Uri(client.StorageUrl,"../"+ account.name),
128
                                Directories=(from container in client.ListContainers(account.name)
129
                                            select new DirectoryRecord
130
                                                        {
131
                                                            DisplayName=container.Name,
132
                                                            Uri = new Uri(client.StorageUrl, "../" + account.name + "/" + container.Name),
133
                                                            Directories=(from folder in client.ListObjects(account.name,container.Name)                                                                        
134
                                                                        select folder).ToTree()
135
                                                        }).ToList()
136
                             };                                                          
137

    
138
            var othersNode = new DirectoryRecord
139
                                 {
140
                                     DisplayName = "Shared to me",
141
                                     Directories=accountNodes.ToList()
142
                                 };
143

    
144
            
145
            var rootItem = new DirectoryRecord
146
                               {
147
                                   DisplayName = AccountName ,
148
                                   Directories = ownFolders.ToList()
149
                               };
150

    
151
            var localFolders = SelectiveExtensions.LocalFolders(AccountName, Account.RootPath,client.StorageUrl.AbsoluteUri);
152

    
153
            AppendToTree(localFolders, rootItem);
154
            
155
            //For each local folder that doesn't exist in the server nodes 
156
            //find the best matching parent and add the folder below it.
157

    
158
            Execute.OnUIThread(() =>
159
                                   {
160
                                       RootNodes.Add(rootItem);
161
                                       RootNodes.Add(othersNode);
162
                                   });
163

    
164
            SetInitialSelections(Account);
165
            
166
            IsBusy = false;
167
        }
168

    
169
        private static void AppendToTree(IEnumerable<DirectoryRecord> localFolders, DirectoryRecord rootItem)
170
        {
171
            foreach (var folder in localFolders)
172
            {
173
                var items = from root in rootItem
174
                            from child in root
175
                            select child;
176
                //If this folder is not included in the server folders
177
                if (items.Any(dir => dir.Uri == folder.Uri)) 
178
                    continue;
179

    
180
                //we need to add it
181
                //Find the best parent
182

    
183
                //One way to do this, is to break the the Uri to its parts
184
                //and try to find a parent using progressively fewer parts
185
                var parts = folder.Uri.AbsoluteUri.Split('/');
186
                for (var i = parts.Length - 1; i > 2; i--)
187
                {
188
                    var parentUrl = String.Join("/", parts.Splice(0, i));
189
                    var parentUri = new Uri(parentUrl);
190

    
191
                    var parent = items.FirstOrDefault(dir => dir.Uri == parentUri);
192
                    if (parent != null)
193
                    {
194
                        parent.Directories.Add(folder);
195
                        break;
196
                    }
197
                }
198
            }
199
        }
200

    
201
        public bool IsBusy
202
        {
203
            get {
204
                return _isBusy;
205
            }
206
            set {
207
                _isBusy = value;
208
                NotifyOfPropertyChange(()=>IsBusy);
209
            }
210
        }
211

    
212
        private void SetInitialSelections(AccountSettings account)
213
        {
214
            var selections = account.SelectiveFolders;
215

    
216

    
217
                
218
            //Initially, all nodes are checked
219
            //We need to *uncheck* the nodes that are not selected
220

    
221
            var allNodes = (from DirectoryRecord rootRecord in RootNodes
222
                           from DirectoryRecord record in rootRecord
223
                           select record).ToList();
224
            //WARNING: Using IsChecked marks the item as REMOVED
225
            allNodes.Apply(record => record.IsExplicitlyChecked = false);
226

    
227
            if (selections.Count == 0)
228
            {
229
            //    allNodes.Apply(record => record.IsChecked = false);
230
                return;
231
            } 
232
            
233
            var selects = (from DirectoryRecord rootRecord in RootNodes
234
                          from DirectoryRecord record in rootRecord
235
                          where record.Uri !=null &&  selections.Contains(record.Uri.ToString())
236
                          select record).ToList();
237
            //var shouldBeChecked = allNodes.Except(selects).ToList();
238
            
239
            //WARNING: Using IsChecked marks the item as ADDED
240
            selects.Apply(record=>record.IsExplicitlyChecked=true);
241

    
242
            //shouldBeChecked.Apply(record => record.IsChecked = true);
243
            
244
            
245

    
246
        }
247

    
248
        protected string AccountName { get; set; }
249

    
250
        public void SaveChanges()
251
        {
252
            var uris = (from DirectoryRecord root in RootNodes
253
                        from DirectoryRecord record in root
254
                        where record.IsChecked == true && record.Uri != null
255
                        select record.Uri).ToArray();            
256

    
257
            SaveSettings(uris);
258
            
259
            //RootNodes is an ObservableCollection, it can't be enumerated iterativelly
260

    
261
            var added = (from DirectoryRecord root in RootNodes
262
                         from DirectoryRecord record in root
263
                         where record.Added && record.Uri != null
264
                         select record.Uri).ToArray();
265
            var removed = (from DirectoryRecord root in RootNodes
266
                           from DirectoryRecord record in root
267
                          where record.Removed && record.Uri != null
268
                         select record.Uri).ToArray();
269
            //TODO: Include Uris for the containers as well
270
            _events.Publish(new SelectiveSynchChanges{Account=Account,Uris=uris,Added=added,Removed=removed});
271
            
272

    
273
            
274

    
275
            TryClose(true);
276
        }
277

    
278
        
279
        private void SaveSettings(IEnumerable<Uri> uris)
280
        {
281
            var selections = uris.Select(uri => uri.ToString()).ToArray();
282

    
283
            Account.SelectiveFolders.Clear();
284
            Account.SelectiveFolders.AddRange(selections);
285
            Settings.Default.Save();            
286
        }        
287

    
288
        public void RejectChanges()
289
        {
290
            TryClose(false);
291
        }
292
    }
293
}