Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / PollAgent.cs @ 268bec7f

History | View | Annotate | Download (31.3 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="PollAgent.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

    
43
using System.Collections.Concurrent;
44
using System.ComponentModel.Composition;
45
using System.Diagnostics;
46
using System.Diagnostics.Contracts;
47
using System.IO;
48
using System.Reflection;
49
using System.Threading;
50
using System.Threading.Tasks;
51
using Castle.ActiveRecord;
52
using Pithos.Interfaces;
53
using Pithos.Network;
54
using log4net;
55

    
56
namespace Pithos.Core.Agents
57
{
58
    using System;
59
    using System.Collections.Generic;
60
    using System.Linq;
61

    
62
    /// <summary>
63
    /// PollAgent periodically polls the server to detect object changes. The agent retrieves a listing of all
64
    /// objects and compares it with a previously cached version to detect differences. 
65
    /// New files are downloaded, missing files are deleted from the local file system and common files are compared
66
    /// to determine the appropriate action
67
    /// </summary>
68
    [Export]
69
    public class PollAgent
70
    {
71
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
72

    
73
        [System.ComponentModel.Composition.Import]
74
        public IStatusKeeper StatusKeeper { get; set; }
75

    
76
        [System.ComponentModel.Composition.Import]
77
        public IPithosSettings Settings { get; set; }
78

    
79
        [System.ComponentModel.Composition.Import]
80
        public NetworkAgent NetworkAgent { get; set; }
81

    
82
        public IStatusNotification StatusNotification { get; set; }
83

    
84
        private bool _firstPoll = true;
85

    
86
        //The Sync Event signals a manual synchronisation
87
        private readonly AsyncManualResetEvent _syncEvent = new AsyncManualResetEvent();
88

    
89
        private readonly ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();
90
        private readonly ConcurrentDictionary<Uri, AccountInfo> _accounts = new ConcurrentDictionary<Uri,AccountInfo>();
91

    
92

    
93
        /// <summary>
94
        /// Start a manual synchronization
95
        /// </summary>
96
        public void SynchNow()
97
        {            
98
            _syncEvent.Set();
99
        }
100

    
101
        /// <summary>
102
        /// Remote files are polled periodically. Any changes are processed
103
        /// </summary>
104
        /// <param name="since"></param>
105
        /// <returns></returns>
106
        public async Task PollRemoteFiles(DateTime? since = null)
107
        {
108
            if (Log.IsDebugEnabled)
109
                Log.DebugFormat("Polling changes after [{0}]",since);
110

    
111
            Debug.Assert(Thread.CurrentThread.IsBackground, "Polling Ended up in the main thread!");
112
            
113

    
114
            using (ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
115
            {
116
                //If this poll fails, we will retry with the same since value
117
                var nextSince = since;
118
                try
119
                {
120
                    UpdateStatus(PithosStatus.PollSyncing);
121

    
122
                    var tasks = from accountInfo in _accounts.Values
123
                                select ProcessAccountFiles(accountInfo, since);
124

    
125
                    var nextTimes=await TaskEx.WhenAll(tasks.ToList());
126

    
127
                    _firstPoll = false;
128
                    //Reschedule the poll with the current timestamp as a "since" value
129

    
130
                    if (nextTimes.Length>0)
131
                        nextSince = nextTimes.Min();
132
                    if (Log.IsDebugEnabled)
133
                        Log.DebugFormat("Next Poll at [{0}]",nextSince);
134
                }
135
                catch (Exception ex)
136
                {
137
                    Log.ErrorFormat("Error while processing accounts\r\n{0}", ex);
138
                    //In case of failure retry with the same "since" value
139
                }
140

    
141
                UpdateStatus(PithosStatus.PollComplete);
142
                //The multiple try blocks are required because we can't have an await call
143
                //inside a finally block
144
                //TODO: Find a more elegant solution for reschedulling in the event of an exception
145
                try
146
                {
147
                    //Wait for the polling interval to pass or the Sync event to be signalled
148
                    nextSince = await WaitForScheduledOrManualPoll(nextSince);
149
                }
150
                finally
151
                {
152
                    //Ensure polling is scheduled even in case of error
153
                    TaskEx.Run(() => PollRemoteFiles(nextSince));                        
154
                }
155
            }
156
        }
157

    
158
        /// <summary>
159
        /// Wait for the polling period to expire or a manual sync request
160
        /// </summary>
161
        /// <param name="since"></param>
162
        /// <returns></returns>
163
        private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
164
        {
165
            var sync = _syncEvent.WaitAsync();
166
            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), NetworkAgent.CancellationToken);
167
            var signaledTask = await TaskEx.WhenAny(sync, wait);
168

    
169
            //Wait for network processing to finish before polling
170
            var pauseTask=NetworkAgent.ProceedEvent.WaitAsync();
171
            await TaskEx.WhenAll(signaledTask, pauseTask);
172

    
173
            //If polling is signalled by SynchNow, ignore the since tag
174
            if (sync.IsCompleted)
175
            {
176
                //TODO: Must convert to AutoReset
177
                _syncEvent.Reset();
178
                return null;
179
            }
180
            return since;
181
        }
182

    
183
        public async Task<DateTime?> ProcessAccountFiles(AccountInfo accountInfo, DateTime? since = null)
184
        {
185
            if (accountInfo == null)
186
                throw new ArgumentNullException("accountInfo");
187
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
188
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
189
            Contract.EndContractBlock();
190

    
191

    
192
            using (ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
193
            {
194

    
195
                await NetworkAgent.GetDeleteAwaiter();
196

    
197
                Log.Info("Scheduled");
198
                var client = new CloudFilesClient(accountInfo);
199

    
200
                //We don't need to check the trash container
201
                var containers = client.ListContainers(accountInfo.UserName)
202
                    .Where(c=>c.Name!="trash")
203
                    .ToList();
204

    
205

    
206
                CreateContainerFolders(accountInfo, containers);
207

    
208
                //The nextSince time fallback time is the same as the current.
209
                //If polling succeeds, the next Since time will be the smallest of the maximum modification times
210
                //of the shared and account objects
211
                var nextSince = since;
212

    
213
                try
214
                {
215
                    //Wait for any deletions to finish
216
                    await NetworkAgent.GetDeleteAwaiter();
217
                    //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
218
                    //than delete a file that was created while we were executing the poll                    
219

    
220
                    //Get the list of server objects changed since the last check
221
                    //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
222
                    var listObjects = (from container in containers
223
                                       select Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
224
                                             client.ListObjects(accountInfo.UserName, container.Name, since), container.Name)).ToList();
225

    
226
                    var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => 
227
                        client.ListSharedObjects(since), "shared");
228
                    listObjects.Add(listShared);
229
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
230

    
231
                    using (ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
232
                    {
233
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
234

    
235
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
236
                        var remoteObjects = (from objectList in listTasks
237
                                            where (string)objectList.AsyncState != "trash"
238
                                            from obj in objectList.Result
239
                                            select obj).ToList();
240
                        
241
                        //Get the latest remote object modification date, only if it is after
242
                        //the original since date
243
                        nextSince = GetLatestDateAfter(nextSince, remoteObjects);
244

    
245
                        var sharedObjects = dict["shared"].Result;
246
                        nextSince = GetLatestDateBefore(nextSince, sharedObjects);
247

    
248
                        //DON'T process trashed files
249
                        //If some files are deleted and added again to a folder, they will be deleted
250
                        //even though they are new.
251
                        //We would have to check file dates and hashes to ensure that a trashed file
252
                        //can be deleted safely from the local hard drive.
253
                        /*
254
                        //Items with the same name, hash may be both in the container and the trash
255
                        //Don't delete items that exist in the container
256
                        var realTrash = from trash in trashObjects
257
                                        where
258
                                            !remoteObjects.Any(
259
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
260
                                        select trash;
261
                        ProcessTrashedFiles(accountInfo, realTrash);
262
*/
263

    
264
                        var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
265
                                            let name = info.Name??""
266
                                            where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
267
                                                  !name.StartsWith(FolderConstants.CacheFolder + "/",
268
                                                                   StringComparison.InvariantCultureIgnoreCase)
269
                                            select info).ToList();
270

    
271
                        if (_firstPoll)
272
                            StatusKeeper.CleanupOrphanStates();
273
                        StatusKeeper.CleanupStaleStates(accountInfo, cleanRemotes);
274
                        
275
                        var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);
276

    
277
                        var filterUris = SelectiveUris[accountInfo.AccountKey];
278

    
279
                        ProcessDeletedFiles(accountInfo, differencer.Deleted.FilterDirectlyBelow(filterUris));
280

    
281
                        // @@@ NEED To add previous state here as well, To compare with previous hash
282

    
283
                        
284

    
285
                        //Create a list of actions from the remote files
286
                        
287
                        var allActions = MovesToActions(accountInfo,differencer.Moved.FilterDirectlyBelow(filterUris))
288
                                        .Union(
289
                                        ChangesToActions(accountInfo, differencer.Changed.FilterDirectlyBelow(filterUris)))
290
                                        .Union(
291
                                        CreatesToActions(accountInfo, differencer.Created.FilterDirectlyBelow(filterUris)));
292

    
293
                        //And remove those that are already being processed by the agent
294
                        var distinctActions = allActions
295
                            .Except(NetworkAgent.GetEnumerable(), new LocalFileComparer())
296
                            .ToList();
297

    
298
                        //Queue all the actions
299
                        foreach (var message in distinctActions)
300
                        {
301
                            NetworkAgent.Post(message);
302
                        }
303

    
304
                        Log.Info("[LISTENER] End Processing");
305
                    }
306
                }
307
                catch (Exception ex)
308
                {
309
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
310
                    return nextSince;
311
                }
312

    
313
                Log.Info("[LISTENER] Finished");
314
                return nextSince;
315
            }
316
        }
317

    
318
        /// <summary>
319
        /// Returns the latest LastModified date from the list of objects, but only if it is before
320
        /// than the threshold value
321
        /// </summary>
322
        /// <param name="threshold"></param>
323
        /// <param name="cloudObjects"></param>
324
        /// <returns></returns>
325
        private static DateTime? GetLatestDateBefore(DateTime? threshold, IList<ObjectInfo> cloudObjects)
326
        {
327
            DateTime? maxDate = null;
328
            if (cloudObjects!=null &&  cloudObjects.Count > 0)
329
                maxDate = cloudObjects.Max(obj => obj.Last_Modified);
330
            if (maxDate == null || maxDate == DateTime.MinValue)
331
                return threshold;
332
            if (threshold == null || threshold == DateTime.MinValue || threshold > maxDate)
333
                return maxDate;
334
            return threshold;
335
        }
336

    
337
        /// <summary>
338
        /// Returns the latest LastModified date from the list of objects, but only if it is after
339
        /// the threshold value
340
        /// </summary>
341
        /// <param name="threshold"></param>
342
        /// <param name="cloudObjects"></param>
343
        /// <returns></returns>
344
        private static DateTime? GetLatestDateAfter(DateTime? threshold, IList<ObjectInfo> cloudObjects)
345
        {
346
            DateTime? maxDate = null;
347
            if (cloudObjects!=null &&  cloudObjects.Count > 0)
348
                maxDate = cloudObjects.Max(obj => obj.Last_Modified);
349
            if (maxDate == null || maxDate == DateTime.MinValue)
350
                return threshold;
351
            if (threshold == null || threshold == DateTime.MinValue || threshold < maxDate)
352
                return maxDate;
353
            return threshold;
354
        }
355

    
356
        readonly AccountsDifferencer _differencer = new AccountsDifferencer();
357
        private Dictionary<Uri, List<Uri>> _selectiveUris = new Dictionary<Uri, List<Uri>>();
358

    
359
        /// <summary>
360
        /// Deletes local files that are not found in the list of cloud files
361
        /// </summary>
362
        /// <param name="accountInfo"></param>
363
        /// <param name="cloudFiles"></param>
364
        private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles)
365
        {
366
            if (accountInfo == null)
367
                throw new ArgumentNullException("accountInfo");
368
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
369
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
370
            if (cloudFiles == null)
371
                throw new ArgumentNullException("cloudFiles");
372
            Contract.EndContractBlock();
373

    
374
            //On the first run
375
            if (_firstPoll)
376
            {
377
                //Only consider files that are not being modified, ie they are in the Unchanged state            
378
                var deleteCandidates = FileState.Queryable.Where(state =>
379
                    state.FilePath.StartsWith(accountInfo.AccountPath)
380
                    && state.FileStatus == FileStatus.Unchanged).ToList();
381

    
382

    
383
                //TODO: filesToDelete must take into account the Others container            
384
                var filesToDelete = (from deleteCandidate in deleteCandidates
385
                                     let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
386
                                     let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
387
                                     where
388
                                         !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)
389
                                     select localFile).ToList();
390

    
391

    
392

    
393
                //Set the status of missing files to Conflict
394
                foreach (var item in filesToDelete)
395
                {
396
                    //Try to acquire a gate on the file, to take into account files that have been dequeued
397
                    //and are being processed
398
                    using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
399
                    {
400
                        if (gate.Failed)
401
                            continue;
402
                        StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted,"Local file missing from server");
403
                    }
404
                }
405
                UpdateStatus(PithosStatus.HasConflicts);
406
                StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted", filesToDelete.Count));
407
                StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count), TraceLevel.Info);
408
            }
409
            else
410
            {
411
                var deletedFiles = new List<FileSystemInfo>();
412
                foreach (var objectInfo in cloudFiles)
413
                {
414
                    if (Log.IsDebugEnabled)
415
                        Log.DebugFormat("Handle deleted [{0}]",objectInfo.Uri);
416
                    var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
417
                    var item = FileAgent.GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);
418
                    if (Log.IsDebugEnabled)
419
                        Log.DebugFormat("Will delete [{0}] for [{1}]", item.FullName,objectInfo.Uri);
420
                    if (item.Exists)
421
                    {
422
                        if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
423
                        {
424
                            item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
425

    
426
                        }
427
                        
428
                        
429
                        Log.DebugFormat("Deleting {0}", item.FullName);
430

    
431
                        var directory = item as DirectoryInfo;
432
                        if (directory!=null)
433
                            directory.Delete(true);
434
                        else
435
                            item.Delete();
436
                        Log.DebugFormat("Deleted [{0}] for [{1}]", item.FullName, objectInfo.Uri);
437
                        DateTime lastDate;
438
                        _lastSeen.TryRemove(item.FullName, out lastDate);
439
                        deletedFiles.Add(item);
440
                    }
441
                    StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted, "File Deleted");
442
                }
443
                Log.InfoFormat("[{0}] files were deleted",deletedFiles.Count);
444
                StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count), TraceLevel.Info);
445
            }
446

    
447
        }
448

    
449
        /// <summary>
450
        /// Creates a Sync action for each changed server file
451
        /// </summary>
452
        /// <param name="accountInfo"></param>
453
        /// <param name="changes"></param>
454
        /// <returns></returns>
455
        private IEnumerable<CloudAction> ChangesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> changes)
456
        {
457
            if (changes == null)
458
                throw new ArgumentNullException();
459
            Contract.EndContractBlock();
460
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
461

    
462
            //In order to avoid multiple iterations over the files, we iterate only once
463
            //over the remote files
464
            foreach (var objectInfo in changes)
465
            {
466
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
467
                //If a directory object already exists, we may need to sync it
468
                if (fileAgent.Exists(relativePath))
469
                {
470
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
471
                    //We don't need to sync directories
472
                    if (objectInfo.IsDirectory && localFile is DirectoryInfo)
473
                        continue;
474
                    using (new SessionScope(FlushAction.Never))
475
                    {
476
                        var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
477
                        _lastSeen[localFile.FullName] = DateTime.Now;
478
                        //Common files should be checked on a per-case basis to detect differences, which is newer
479

    
480
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
481
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
482
                                                     accountInfo.BlockHash);
483
                    }
484
                }
485
                else
486
                {
487
                    //Remote files should be downloaded
488
                    yield return new CloudDownloadAction(accountInfo, objectInfo);
489
                }
490
            }
491
        }
492

    
493
        /// <summary>
494
        /// Creates a Local Move action for each moved server file
495
        /// </summary>
496
        /// <param name="accountInfo"></param>
497
        /// <param name="moves"></param>
498
        /// <returns></returns>
499
        private IEnumerable<CloudAction> MovesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> moves)
500
        {
501
            if (moves == null)
502
                throw new ArgumentNullException();
503
            Contract.EndContractBlock();
504
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
505

    
506
            //In order to avoid multiple iterations over the files, we iterate only once
507
            //over the remote files
508
            foreach (var objectInfo in moves)
509
            {
510
                var previousRelativepath = objectInfo.Previous.RelativeUrlToFilePath(accountInfo.UserName);
511
                //If the previous file already exists, we can execute a Move operation
512
                if (fileAgent.Exists(previousRelativepath))
513
                {
514
                    var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
515
                    using (new SessionScope(FlushAction.Never))
516
                    {
517
                        var state = StatusKeeper.GetStateByFilePath(previousFile.FullName);
518
                        _lastSeen[previousFile.FullName] = DateTime.Now;
519

    
520
                        //For each moved object we need to move both the local file and update                                                
521
                        yield return new CloudAction(accountInfo, CloudActionType.RenameLocal,
522
                                                     previousFile, objectInfo, state, accountInfo.BlockSize,
523
                                                     accountInfo.BlockHash);
524
                        //For modified files, we need to download the changes as well
525
                        if (objectInfo.Hash!=objectInfo.PreviousHash)
526
                            yield return new CloudDownloadAction(accountInfo,objectInfo);
527
                    }
528
                }
529
                //If the previous file does not exist, we need to download it in the new location
530
                else
531
                {
532
                    //Remote files should be downloaded
533
                    yield return new CloudDownloadAction(accountInfo, objectInfo);
534
                }
535
            }
536
        }
537

    
538

    
539
        /// <summary>
540
        /// Creates a download action for each new server file
541
        /// </summary>
542
        /// <param name="accountInfo"></param>
543
        /// <param name="creates"></param>
544
        /// <returns></returns>
545
        private IEnumerable<CloudAction> CreatesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> creates)
546
        {
547
            if (creates == null)
548
                throw new ArgumentNullException();
549
            Contract.EndContractBlock();
550
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
551

    
552
            //In order to avoid multiple iterations over the files, we iterate only once
553
            //over the remote files
554
            foreach (var objectInfo in creates)
555
            {
556
                if (Log.IsDebugEnabled)
557
                    Log.DebugFormat("[NEW INFO] {0}",objectInfo.Uri);
558

    
559
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
560

    
561
                //If the object already exists, we should check before uploading or downloading
562
                if (fileAgent.Exists(relativePath))
563
                {
564
                    var localFile= fileAgent.GetFileSystemInfo(relativePath);
565
                    var state = StatusKeeper.GetStateByFilePath(localFile.WithProperCapitalization().FullName);
566
                    yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
567
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
568
                                                     accountInfo.BlockHash);                    
569
                }
570
                else
571
                {
572
                    //Remote files should be downloaded
573
                    yield return new CloudDownloadAction(accountInfo, objectInfo);
574
                }
575

    
576
            }
577
        }
578

    
579
        /// <summary>
580
        /// Notify the UI to update the visual status
581
        /// </summary>
582
        /// <param name="status"></param>
583
        private void UpdateStatus(PithosStatus status)
584
        {
585
            try
586
            {
587
                StatusNotification.SetPithosStatus(status);
588
                //StatusNotification.Notify(new Notification());
589
            }
590
            catch (Exception exc)
591
            {
592
                //Failure is not critical, just log it
593
                Log.Warn("Error while updating status", exc);
594
            }
595
        }
596

    
597
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
598
        {
599
            var containerPaths = from container in containers
600
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
601
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
602
                                 select containerPath;
603

    
604
            foreach (var path in containerPaths)
605
            {
606
                Directory.CreateDirectory(path);
607
            }
608
        }
609

    
610
        public void SetSyncUris(Uri accountKey, Uri[] uris)
611
        {            
612
            SelectiveUris[accountKey]=uris.ToList();
613
        }
614

    
615
        protected Dictionary<Uri,List<Uri>> SelectiveUris
616
        {
617
            get { return _selectiveUris;}
618
            set { _selectiveUris = value; }
619
        }
620

    
621
        public void AddAccount(AccountInfo accountInfo)
622
        {
623
            //Avoid adding a duplicate accountInfo
624
            _accounts.TryAdd(accountInfo.AccountKey, accountInfo);
625
        }
626

    
627
        public void RemoveAccount(AccountInfo accountInfo)
628
        {
629
            AccountInfo account;
630
            _accounts.TryRemove(accountInfo.AccountKey, out account);
631
            SnapshotDifferencer differencer;
632
            _differencer.Differencers.TryRemove(accountInfo.AccountKey, out differencer);
633
        }
634

    
635
        public void SetSelectivePaths(AccountInfo accountInfo,Uri[] added, Uri[] removed)
636
        {
637
            AbortRemovedPaths(accountInfo,removed);
638
            DownloadNewPaths(accountInfo,added);
639
        }
640

    
641
        private void DownloadNewPaths(AccountInfo accountInfo, Uri[] added)
642
        {
643
            var client = new CloudFilesClient(accountInfo);
644
            foreach (var folderUri in added)
645
            {
646
                string account;
647
                string container;
648
                var segmentsCount = folderUri.Segments.Length;
649
                if (segmentsCount < 3)
650
                    continue;
651
                if (segmentsCount==3)
652
                {
653
                    account = folderUri.Segments[1].TrimEnd('/');
654
                    container = folderUri.Segments[2].TrimEnd('/');                    
655
                }
656
                else
657
                {
658
                    account = folderUri.Segments[2].TrimEnd('/');
659
                    container = folderUri.Segments[3].TrimEnd('/');                    
660
                }
661
                IList<ObjectInfo> items;
662
                if(segmentsCount>3)
663
                {
664
                    var folder =String.Join("", folderUri.Segments.Splice(4));
665
                    items = client.ListObjects(account, container, folder);
666
                }
667
                else
668
                {
669
                    items = client.ListObjects(account, container);
670
                }
671
                var actions=CreatesToActions(accountInfo, items);
672
                foreach (var action in actions)
673
                {
674
                    NetworkAgent.Post(action);    
675
                }                
676
            }
677

    
678
            //Need to get a listing of each of the URLs, then post them to the NetworkAgent
679
            //CreatesToActions(accountInfo,)
680

    
681
/*            NetworkAgent.Post();*/
682
        }
683

    
684
        private void AbortRemovedPaths(AccountInfo accountInfo, Uri[] removed)
685
        {
686
            /*this.NetworkAgent.*/
687
        }
688
    }
689
}