Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / PollAgent.cs @ 4b58c004

History | View | Annotate | Download (54.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.Linq.Expressions;
49
using System.Reflection;
50
using System.Security.Cryptography;
51
using System.Threading;
52
using System.Threading.Tasks;
53
using System.Threading.Tasks.Dataflow;
54
using Castle.ActiveRecord;
55
using Pithos.Interfaces;
56
using Pithos.Network;
57
using log4net;
58

    
59
namespace Pithos.Core.Agents
60
{
61
    using System;
62
    using System.Collections.Generic;
63
    using System.Linq;
64

    
65
    public class PollRequest
66
    {
67
        public DateTime? Since { get; set; }
68
        public IEnumerable<string> Batch { get; set; }
69
    }
70

    
71
    [DebuggerDisplay("{FilePath} C:{C} L:{L} S:{S}")]
72
    public class StateTuple
73
    {
74
        public string FilePath { get; private set; }
75

    
76
        public string MD5 { get; set; }
77

    
78
        public string L
79
        {
80
            get { return FileState==null?null:FileState.Checksum; }
81
        }
82

    
83
        private string _c;
84
        public string C
85
        {
86
            get { return _c; }
87
            set {
88
                _c = String.IsNullOrWhiteSpace(value) ? null : value;
89
            }
90
        }
91

    
92
        public string S
93
        {
94
            get { return ObjectInfo == null ? null : ObjectInfo.X_Object_Hash; }
95
        }
96

    
97
        private FileSystemInfo _fileInfo;
98
        private TreeHash _merkle;
99

    
100
        public FileSystemInfo FileInfo
101
        {
102
            get { return _fileInfo; }
103
            set
104
            {
105
                _fileInfo = value;
106
                FilePath = value.FullName;
107
            }
108
        }
109

    
110
        public FileState FileState { get; set; }
111
        public ObjectInfo ObjectInfo{ get; set; }
112

    
113

    
114
        public TreeHash Merkle
115
        {
116
            get {
117
                return _merkle;
118
            }
119
            set {
120
                _merkle = value;
121
                C = _merkle.TopHash.ToHashString();
122
            }
123
        }
124

    
125
        public StateTuple() { }
126

    
127
        public StateTuple(FileSystemInfo info)
128
        {
129
            FileInfo = info;
130
        }
131

    
132

    
133
    }
134

    
135

    
136
    /// <summary>
137
    /// PollAgent periodically polls the server to detect object changes. The agent retrieves a listing of all
138
    /// objects and compares it with a previously cached version to detect differences. 
139
    /// New files are downloaded, missing files are deleted from the local file system and common files are compared
140
    /// to determine the appropriate action
141
    /// </summary>
142
    [Export]
143
    public class PollAgent
144
    {
145
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
146

    
147
        [System.ComponentModel.Composition.Import]
148
        public IStatusKeeper StatusKeeper { get; set; }
149

    
150
        [System.ComponentModel.Composition.Import]
151
        public IPithosSettings Settings { get; set; }
152

    
153
        [System.ComponentModel.Composition.Import]
154
        public NetworkAgent NetworkAgent { get; set; }
155

    
156
        [System.ComponentModel.Composition.Import]
157
        public Selectives Selectives { get; set; }
158

    
159
        public IStatusNotification StatusNotification { get; set; }
160

    
161
        private CancellationTokenSource _currentOperationCancellation = new CancellationTokenSource();
162

    
163
        public void CancelCurrentOperation()
164
        {
165
            //What does it mean to cancel the current upload/download?
166
            //Obviously, the current operation will be cancelled by throwing
167
            //a cancellation exception.
168
            //
169
            //The default behavior is to retry any operations that throw.
170
            //Obviously this is not what we want in this situation.
171
            //The cancelled operation should NOT bea retried. 
172
            //
173
            //This can be done by catching the cancellation exception
174
            //and avoiding the retry.
175
            //
176

    
177
            //Have to reset the cancellation source - it is not possible to reset the source
178
            //Have to prevent a case where an operation requests a token from the old source
179
            var oldSource = Interlocked.Exchange(ref _currentOperationCancellation, new CancellationTokenSource());
180
            oldSource.Cancel();
181

    
182
        }
183

    
184
        public bool Pause
185
        {
186
            get {
187
                return _pause;
188
            }
189
            set {
190
                _pause = value;                
191
                if (!_pause)
192
                    _unPauseEvent.Set();
193
                else
194
                {
195
                    _unPauseEvent.Reset();
196
                }
197
            }
198
        }
199

    
200
        private bool _firstPoll = true;
201

    
202
        //The Sync Event signals a manual synchronisation
203
        private readonly AsyncManualResetEvent _syncEvent = new AsyncManualResetEvent();
204

    
205
        private readonly AsyncManualResetEvent _unPauseEvent = new AsyncManualResetEvent(true);
206

    
207
        private readonly ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();
208
        private readonly ConcurrentDictionary<Uri, AccountInfo> _accounts = new ConcurrentDictionary<Uri,AccountInfo>();
209

    
210
        //private readonly ActionBlock<PollRequest>  _pollAction;
211

    
212
        public PollAgent()
213
        {
214
            //_pollAction=new ActionBlock<PollRequest>(p=>ProcessPollRequest(p));
215
        }
216

    
217

    
218
        /*private void ProcessPollRequest(PollRequest request)
219
        {
220

    
221
            if (request.Since == null && request.Batch != null)
222
            {
223
                _batchQueue.Enqueue(request.Batch);
224
                _syncEvent.Set();                
225
            }
226
            else 
227
            {
228
                PollRemoteFiles(request.Since).Wait();
229
            }
230
        }*/
231
        /// <summary>
232
        /// Start a manual synchronization
233
        /// </summary>
234
        public void SynchNow(IEnumerable<string> paths=null)
235
        {
236
            _batchQueue.Enqueue(paths);
237
            _syncEvent.Set();                
238

    
239
            //_pollAction.Post(new PollRequest {Batch = paths});
240
        }
241

    
242
        readonly ConcurrentQueue<IEnumerable<string>> _batchQueue=new ConcurrentQueue<IEnumerable<string>>();
243

    
244
        /// <summary>
245
        /// Remote files are polled periodically. Any changes are processed
246
        /// </summary>
247
        /// <param name="since"></param>
248
        /// <returns></returns>
249
        public  void PollRemoteFiles(DateTime? since = null)
250
        {
251
            if (Log.IsDebugEnabled)
252
                Log.DebugFormat("Polling changes after [{0}]",since);
253

    
254
            Debug.Assert(Thread.CurrentThread.IsBackground, "Polling Ended up in the main thread!");
255

    
256
            //GC.Collect();
257

    
258
            using (ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
259
            {
260
                //If this poll fails, we will retry with the same since value
261
                var nextSince = since;
262
                try
263
                {
264
                    _unPauseEvent.Wait();
265
                    UpdateStatus(PithosStatus.PollSyncing);
266

    
267
                    var accountBatches=new Dictionary<Uri, IEnumerable<string>>();
268
                    IEnumerable<string> batch = null;
269
                    if (_batchQueue.TryDequeue(out batch) && batch != null)
270
                        foreach (var account in _accounts.Values)
271
                        {
272
                            var accountBatch = batch.Where(path => path.IsAtOrBelow(account.AccountPath));
273
                            accountBatches[account.AccountKey] = accountBatch;
274
                        }
275

    
276

    
277
                    IEnumerable<Task<DateTime?>> tasks = new List<Task<DateTime?>>();
278
                    foreach(var accountInfo in _accounts.Values)
279
                    {
280
                        IEnumerable<string> accountBatch ;
281
                        accountBatches.TryGetValue(accountInfo.AccountKey,out accountBatch);
282
                        ProcessAccountFiles (accountInfo, accountBatch, since).Wait();
283
                    }
284

    
285
                    var nextTimes=TaskEx.WhenAll(tasks.ToList()).Result;
286

    
287
                    _firstPoll = false;
288
                    //Reschedule the poll with the current timestamp as a "since" value
289

    
290
                    if (nextTimes.Length>0)
291
                        nextSince = nextTimes.Min();
292
                    if (Log.IsDebugEnabled)
293
                        Log.DebugFormat("Next Poll at [{0}]",nextSince);
294
                }
295
                catch (Exception ex)
296
                {
297
                    Log.ErrorFormat("Error while processing accounts\r\n{0}", ex);
298
                    //In case of failure retry with the same "since" value
299
                }
300

    
301
                UpdateStatus(PithosStatus.PollComplete);
302
                //The multiple try blocks are required because we can't have an await call
303
                //inside a finally block
304
                //TODO: Find a more elegant solution for reschedulling in the event of an exception
305
                try
306
                {
307
                    //Wait for the polling interval to pass or the Sync event to be signalled
308
                    nextSince = WaitForScheduledOrManualPoll(nextSince).Result;
309
                }
310
                finally
311
                {
312
                    //Ensure polling is scheduled even in case of error
313
                    PollRemoteFiles(nextSince);
314
                    //_pollAction.Post(new PollRequest {Since = nextSince});
315
                }
316
            }
317
        }
318

    
319
        /// <summary>
320
        /// Wait for the polling period to expire or a manual sync request
321
        /// </summary>
322
        /// <param name="since"></param>
323
        /// <returns></returns>
324
        private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
325
        {
326
            var sync = _syncEvent.WaitAsync();
327
            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval));
328
            
329
            var signaledTask = await TaskEx.WhenAny(sync, wait);
330
            
331
            //Pausing takes precedence over manual sync or awaiting
332
            _unPauseEvent.Wait();
333
            
334
            //Wait for network processing to finish before polling
335
            var pauseTask=NetworkAgent.ProceedEvent.WaitAsync();
336
            await TaskEx.WhenAll(signaledTask, pauseTask);
337

    
338
            //If polling is signalled by SynchNow, ignore the since tag
339
            if (sync.IsCompleted)
340
            {
341
                //TODO: Must convert to AutoReset
342
                _syncEvent.Reset();
343
                return null;
344
            }
345
            return since;
346
        }
347

    
348
        public async Task<DateTime?> ProcessAccountFiles(AccountInfo accountInfo, IEnumerable<string> accountBatch, DateTime? since = null)
349
        {
350
            if (accountInfo == null)
351
                throw new ArgumentNullException("accountInfo");
352
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
353
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
354
            Contract.EndContractBlock();
355

    
356

    
357
            using (ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
358
            {
359

    
360
                await NetworkAgent.GetDeleteAwaiter();
361

    
362
                Log.Info("Scheduled");
363
                var client = new CloudFilesClient(accountInfo);
364

    
365
                //We don't need to check the trash container
366
                var containers = client.ListContainers(accountInfo.UserName)
367
                    .Where(c=>c.Name!="trash")
368
                    .ToList();
369

    
370

    
371
                CreateContainerFolders(accountInfo, containers);
372

    
373
                //The nextSince time fallback time is the same as the current.
374
                //If polling succeeds, the next Since time will be the smallest of the maximum modification times
375
                //of the shared and account objects
376
                var nextSince = since;
377

    
378
                try
379
                {
380
                    //Wait for any deletions to finish
381
                    await NetworkAgent.GetDeleteAwaiter();
382
                    //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
383
                    //than delete a file that was created while we were executing the poll                    
384

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

    
391
                    var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => 
392
                        client.ListSharedObjects(since), "shared");
393
                    listObjects.Add(listShared);
394
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
395

    
396
                    using (ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
397
                    {
398
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
399

    
400
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
401
                        var remoteObjects = (from objectList in listTasks
402
                                            where (string)objectList.AsyncState != "trash"
403
                                            from obj in objectList.Result
404
                                            orderby obj.Bytes ascending 
405
                                            select obj).ToList();
406
                        
407
                        //Get the latest remote object modification date, only if it is after
408
                        //the original since date
409
                        nextSince = GetLatestDateAfter(nextSince, remoteObjects);
410

    
411
                        var sharedObjects = dict["shared"].Result;
412
                        nextSince = GetLatestDateBefore(nextSince, sharedObjects);
413

    
414
                        //DON'T process trashed files
415
                        //If some files are deleted and added again to a folder, they will be deleted
416
                        //even though they are new.
417
                        //We would have to check file dates and hashes to ensure that a trashed file
418
                        //can be deleted safely from the local hard drive.
419
                        /*
420
                        //Items with the same name, hash may be both in the container and the trash
421
                        //Don't delete items that exist in the container
422
                        var realTrash = from trash in trashObjects
423
                                        where
424
                                            !remoteObjects.Any(
425
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
426
                                   8     select trash;
427
                        ProcessTrashedFiles(accountInfo, realTrash);
428
*/
429

    
430
                        var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
431
                                            let name = info.Name??""
432
                                            where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
433
                                                  !name.StartsWith(FolderConstants.CacheFolder + "/",
434
                                                                   StringComparison.InvariantCultureIgnoreCase)
435
                                            select info).ToList();
436

    
437
                        if (_firstPoll)
438
                            StatusKeeper.CleanupOrphanStates();
439
                        StatusKeeper.CleanupStaleStates(accountInfo, cleanRemotes);
440
                        
441
                        //var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);
442

    
443
                        //var filterUris = Selectives.SelectiveUris[accountInfo.AccountKey];
444

    
445
                        //May have to wait if the FileAgent has asked for a Pause, due to local changes
446
                        await _unPauseEvent.WaitAsync();
447

    
448
                        //Get the local files here                        
449
                        var agent = AgentLocator<FileAgent>.Get(accountInfo.AccountPath);                        
450
                        //TODO: Pass the batch here as well
451
                        var files = await LoadLocalFileTuples(accountInfo, accountBatch);
452

    
453
                        var states = FileState.Queryable.ToList();                        
454
                        
455
                        var infos = (from remote in cleanRemotes
456
                                    let path = remote.RelativeUrlToFilePath(accountInfo.UserName)
457
                                    let info=agent.GetFileSystemInfo(path)
458
                                    select Tuple.Create(info.FullName,remote))
459
                                    .ToList();
460

    
461
                        var token = _currentOperationCancellation.Token;
462

    
463
                        var tuples = MergeSources(infos, files, states).ToList();
464

    
465
                        //Process only the changes in the batch file, if one exists
466
                        var stateTuples = accountBatch==null?tuples:tuples.Where(t => accountBatch.Contains(t.FilePath));
467
                        foreach (var tuple in stateTuples)
468
                        {
469
                            await _unPauseEvent.WaitAsync();
470

    
471
                            //Set the Merkle Hash
472
                            SetMerkleHash(accountInfo, tuple);
473

    
474
                            SyncSingleItem(accountInfo, tuple, agent, token);
475

    
476
                        }
477

    
478

    
479
                        //On the first run
480
/*
481
                        if (_firstPoll)
482
                        {
483
                            MarkSuspectedDeletes(accountInfo, cleanRemotes);
484
                        }
485
*/
486

    
487

    
488
                        Log.Info("[LISTENER] End Processing");
489
                    }
490
                }
491
                catch (Exception ex)
492
                {
493
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
494
                    return nextSince;
495
                }
496

    
497
                Log.Info("[LISTENER] Finished");
498
                return nextSince;
499
            }
500
        }
501

    
502
        private static void SetMerkleHash(AccountInfo accountInfo, StateTuple tuple)
503
        {
504
            //The Merkle hash for directories is that of an empty buffer
505
            if (tuple.FileInfo is DirectoryInfo)
506
                tuple.C = MERKLE_EMPTY;
507
            else if (tuple.FileState != null && tuple.MD5 == tuple.FileState.ShortHash)
508
            {
509
                //If there is a state whose MD5 matches, load the merkle hash from the file state
510
                //insteaf of calculating it
511
                tuple.C = tuple.FileState.Checksum;                              
512
            }
513
            else
514
            {
515
                tuple.Merkle = TaskEx.Run(()=> Signature.CalculateTreeHash(tuple.FileInfo, accountInfo.BlockSize, accountInfo.BlockHash)).Result;
516
                //tuple.C=tuple.Merkle.TopHash.ToHashString();                
517
            }
518
        }
519

    
520
        private async Task<List<Tuple<FileSystemInfo, string>>> LoadLocalFileTuples(AccountInfo accountInfo,IEnumerable<string> batch )
521
        {
522
            using (ThreadContext.Stacks["Account Files Hashing"].Push(accountInfo.UserName))
523
            {
524
                var batchPaths = (batch==null)?new List<string>():batch.ToList();
525
                IEnumerable<FileSystemInfo> localInfos=AgentLocator<FileAgent>.Get(accountInfo.AccountPath)
526
                                                        .EnumerateFileSystemInfos();
527
                if (batchPaths.Count>0)
528
                    localInfos= localInfos.Where(fi => batchPaths.Contains(fi.FullName));
529
                
530
                //Use the queue to retry locked file hashing
531
                var fileQueue = new Queue<FileSystemInfo>(localInfos);
532
                var hasher = MD5.Create();
533

    
534
                var results = new List<Tuple<FileSystemInfo, string>>();
535
                var backoff = 0;
536
                while (fileQueue.Count > 0)
537
                {
538
                    var file = fileQueue.Dequeue();
539
                    using (ThreadContext.Stacks["File"].Push(file.FullName))
540
                    {
541
                        /*
542
                                                Signature.CalculateTreeHash(file, accountInfo.BlockSize,
543
                                                                                                 accountInfo.BlockHash).
544
                                                                         TopHash.ToHashString()
545
                        */
546
                        try
547
                        {
548
                            //Replace MD5 here, do the calc while syncing individual files
549
                            string hash ;
550
                            if (file is DirectoryInfo)
551
                                hash = MERKLE_EMPTY;
552
                            else
553
                            {
554
                                //Wait in case the FileAgent has requested a Pause
555
                                await _unPauseEvent.WaitAsync();
556
                                
557
                                using (StatusNotification.GetNotifier("Hashing {0}", "Finished hashing {0}", file.Name))
558
                                using (var stream = (file as FileInfo).OpenRead())
559
                                {                                    
560
                                    hash = hasher.ComputeHash(stream).ToHashString();
561
                                    backoff = 0;
562
                                }
563
                            }                            
564
                            results.Add(Tuple.Create(file, hash));
565
                        }
566
                        catch (IOException exc)
567
                        {
568
                            Log.WarnFormat("[HASH] File in use, will retry [{0}]", exc);
569
                            fileQueue.Enqueue(file);
570
                            //If this is the only enqueued file                            
571
                            if (fileQueue.Count != 1) continue;
572
                            
573
                            
574
                            //Increase delay
575
                            if (backoff<60000)
576
                                backoff += 10000;
577
                            //Pause Polling for the specified time
578
                        }
579
                        if (backoff>0)
580
                            await PauseFor(backoff);
581
                    }
582
                }
583

    
584
                return results;
585
            }
586
        }
587

    
588
        /// <summary>
589
        /// Wait and Pause the agent while waiting
590
        /// </summary>
591
        /// <param name="backoff"></param>
592
        /// <returns></returns>
593
        private async Task PauseFor(int backoff)
594
        {
595

    
596
            Pause = true;
597
            await TaskEx.Delay(backoff);
598
            Pause = false;
599
        }
600

    
601
        private void SyncSingleItem(AccountInfo accountInfo, StateTuple tuple, FileAgent agent, CancellationToken token)
602
        {
603
            Log.DebugFormat("Sync [{0}] C:[{1}] L:[{2}] S:[{3}]",tuple.FilePath,tuple.C,tuple.L,tuple.S);
604

    
605
            var localFilePath = tuple.FilePath;
606
            //Don't use the tuple info, it may have been deleted
607
            var localInfo = FileInfoExtensions.FromPath(localFilePath);
608

    
609

    
610
            var isUnselectedRootFolder = agent.IsUnselectedRootFolder(tuple.FilePath);
611

    
612
            //Unselected root folders that have not yet been uploaded should be uploaded and added to the 
613
            //selective folders
614

    
615
            if (!Selectives.IsSelected(accountInfo, localFilePath) && !(isUnselectedRootFolder && tuple.ObjectInfo==null) )                
616
                return;
617

    
618
            // Local file unchanged? If both C and L are null, make sure it's because 
619
            //both the file is missing and the state checksum is not missing
620
            if (tuple.C == tuple.L /*&& (localInfo.Exists || tuple.FileState == null)*/)
621
            {
622
                //No local changes
623
                //Server unchanged?
624
                if (tuple.S == tuple.L)
625
                {
626
                    // No server changes
627
                    //Has the file been renamed on the server?
628
                    MoveForServerMove(accountInfo, tuple);
629
                }
630
                else
631
                {
632
                    //Different from server
633
                    //Does the server file exist?
634
                    if (tuple.S == null)
635
                    {
636
                        //Server file doesn't exist
637
                        //deleteObjectFromLocal()
638
                        StatusKeeper.SetFileState(localFilePath, FileStatus.Deleted,
639
                                                  FileOverlayStatus.Deleted, "");
640
                        agent.Delete(localFilePath);
641
                        //updateRecord(Remove C, L)
642
                        StatusKeeper.ClearFileStatus(localFilePath);
643
                    }
644
                    else
645
                    {
646
                        //Server file exists
647
                        //downloadServerObject() // Result: L = S
648
                        //If the file has moved on the server, move it locally before downloading
649
                        var targetPath = MoveForServerMove(accountInfo, tuple);
650

    
651
                        StatusKeeper.SetFileState(targetPath, FileStatus.Modified,
652
                                                  FileOverlayStatus.Modified, "");
653
                        NetworkAgent.Downloader.DownloadCloudFile(accountInfo,
654
                                                                  tuple.ObjectInfo,
655
                                                                  targetPath, tuple.Merkle, token).Wait(token);
656
                        //updateRecord( L = S )
657
                        StatusKeeper.UpdateFileChecksum(targetPath, tuple.ObjectInfo.ETag,
658
                                                        tuple.ObjectInfo.X_Object_Hash);
659

    
660
                        StatusKeeper.StoreInfo(targetPath, tuple.ObjectInfo);
661

    
662
                        /*
663
                                                        StatusKeeper.SetFileState(targetPath, FileStatus.Unchanged,
664
                                                                                  FileOverlayStatus.Normal, "");
665
                            */
666
                    }
667
                }
668

    
669
            }
670
            else
671
            {
672
                //Local changes found
673

    
674
                //Server unchanged?
675
                if (tuple.S == tuple.L)
676
                {
677
                    //The FileAgent selective sync checks for new root folder files
678
                    if (!agent.Ignore(localFilePath))
679
                    {
680
                        if ((tuple.C == null || !localInfo.Exists) && tuple.ObjectInfo != null)
681
                        {
682
                            //deleteObjectFromServer()
683
                            DeleteCloudFile(accountInfo, tuple);
684
                            //updateRecord( Remove L, S)                  
685
                        }
686
                        else
687
                        {
688
                            //uploadLocalObject() // Result: S = C, L = S                        
689

    
690
                            //Debug.Assert(tuple.FileState !=null);
691
                            var action = new CloudUploadAction(accountInfo, localInfo, tuple.FileState,
692
                                                               accountInfo.BlockSize, accountInfo.BlockHash,
693
                                                               "Poll", isUnselectedRootFolder);
694
                            NetworkAgent.Uploader.UploadCloudFile(action, tuple.Merkle, token).Wait(token);
695

    
696
                            //updateRecord( S = C )
697
                            //State updated by the uploader
698

    
699
                            if (isUnselectedRootFolder)
700
                            {
701
                                ProcessChildren(accountInfo, tuple, agent, token);
702
                            }
703
                        }
704
                    }
705
                }
706
                else
707
                {
708
                    if (tuple.C == tuple.S)
709
                    {
710
                        // (Identical Changes) Result: L = S
711
                        //doNothing()
712
                        //Detect server moves
713
                        var targetPath = MoveForServerMove(accountInfo, tuple);
714
                        StatusKeeper.StoreInfo(targetPath, tuple.ObjectInfo);
715
                    }
716
                    else
717
                    {
718
                        if ((tuple.C == null || !localInfo.Exists) && tuple.ObjectInfo != null)
719
                        {
720
                            //deleteObjectFromServer()
721
                            DeleteCloudFile(accountInfo, tuple);
722
                            //updateRecord(Remove L, S)                  
723
                        }
724
                            //If both the local and server files are missing, the state is stale
725
                        else if (!localInfo.Exists && (tuple.S == null || tuple.ObjectInfo == null))
726
                        {
727
                            StatusKeeper.ClearFileStatus(localInfo.FullName);
728
                        }
729
                        else
730
                        {
731
                            ReportConflictForMismatch(localFilePath);
732
                            //identifyAsConflict() // Manual action required
733
                        }
734
                    }
735
                }
736
            }
737
        }
738

    
739
        private string MoveForServerMove(AccountInfo accountInfo, StateTuple tuple)
740
        {
741
            if (tuple.ObjectInfo == null)
742
                return null;
743
            var relativePath = tuple.ObjectInfo.RelativeUrlToFilePath(accountInfo.UserName);
744
            var serverPath = Path.Combine(accountInfo.AccountPath, relativePath);
745
            
746
            //Compare Case Insensitive
747
            if (String.Equals(tuple.FilePath ,serverPath,StringComparison.InvariantCultureIgnoreCase)) return serverPath;
748

    
749
            if (tuple.FileInfo.Exists)
750
            {                    
751
                var fi = tuple.FileInfo as FileInfo;
752
                if (fi != null)
753
                    fi.MoveTo(serverPath);
754
                var di = tuple.FileInfo as DirectoryInfo;
755
                if (di != null)
756
                    di.MoveTo(serverPath);
757
                StatusKeeper.StoreInfo(serverPath, tuple.ObjectInfo);
758
            }
759
            else
760
            {
761
                Debug.Assert(false, "File does not exist");
762
            }
763
            return serverPath;
764
        }
765

    
766
        private void DeleteCloudFile(AccountInfo accountInfo, StateTuple tuple)
767
        {
768
            StatusKeeper.SetFileState(tuple.FilePath, FileStatus.Deleted,
769
                                      FileOverlayStatus.Deleted, "");
770
            NetworkAgent.DeleteAgent.DeleteCloudFile(accountInfo, tuple.ObjectInfo);
771
            StatusKeeper.ClearFileStatus(tuple.FilePath);
772
        }
773

    
774
        private void ProcessChildren(AccountInfo accountInfo, StateTuple tuple, FileAgent agent, CancellationToken token)
775
        {
776

    
777
            var dirInfo = tuple.FileInfo as DirectoryInfo;
778
            var folderTuples = from folder in dirInfo.EnumerateDirectories("*", SearchOption.AllDirectories)
779
                               select new StateTuple(folder);
780
            var fileTuples = from file in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories)
781
                             select new StateTuple(file);
782
            
783
            //Process folders first, to ensure folders appear on the sever as soon as possible
784
            folderTuples.ApplyAction(t => SyncSingleItem(accountInfo, t, agent, token));
785
            
786
            fileTuples.ApplyAction(t => SyncSingleItem(accountInfo, t, agent, token));
787
        }
788

    
789
        private static IEnumerable<StateTuple> MergeSources(
790
            IEnumerable<Tuple<string, ObjectInfo>> infos, 
791
            IEnumerable<Tuple<FileSystemInfo, string>> files, 
792
            IEnumerable<FileState> states)
793
        {
794
            var tuplesByPath = new Dictionary<string, StateTuple>();
795
            foreach (var file in files)
796
            {
797
                var fsInfo = file.Item1;
798
                var fileHash = fsInfo is DirectoryInfo? MERKLE_EMPTY:file.Item2;
799

    
800
                tuplesByPath[fsInfo.FullName] = new StateTuple {FileInfo = fsInfo, MD5 = fileHash};
801
            }
802
            foreach (var state in states)
803
            {
804
                StateTuple hashTuple;
805
                if (tuplesByPath.TryGetValue(state.FilePath, out hashTuple))
806
                {
807
                    hashTuple.FileState = state;
808
                }
809
                else
810
                {
811
                    var fsInfo = FileInfoExtensions.FromPath(state.FilePath);
812
                    tuplesByPath[state.FilePath] = new StateTuple {FileInfo = fsInfo, FileState = state};
813
                }
814
            }
815

    
816
            var tuplesByID = tuplesByPath.Values
817
                .Where(tuple => tuple.FileState != null && tuple.FileState.ObjectID!=null)
818
                .ToDictionary(tuple=>tuple.FileState.ObjectID,tuple=>tuple);//new Dictionary<Guid, StateTuple>();
819

    
820
            foreach (var info in infos)
821
            {
822
                StateTuple hashTuple;
823
                var filePath = info.Item1;
824
                var objectInfo = info.Item2;
825
                var objectID = objectInfo.UUID;
826

    
827
                if (tuplesByID.TryGetValue(objectID, out hashTuple))
828
                {
829
                    hashTuple.ObjectInfo = objectInfo;                    
830
                }
831
                else if (tuplesByPath.TryGetValue(filePath, out hashTuple))
832
                {
833
                    hashTuple.ObjectInfo = objectInfo;
834
                }
835
                else
836
                {
837
                    var fsInfo = FileInfoExtensions.FromPath(filePath);
838
                    var tuple = new StateTuple {FileInfo = fsInfo, ObjectInfo = objectInfo};
839
                    tuplesByPath[filePath] = tuple;
840
                    tuplesByID[objectInfo.UUID] = tuple;
841
                }
842
            }
843
            return tuplesByPath.Values;
844
        }
845

    
846
        /// <summary>
847
        /// Returns the latest LastModified date from the list of objects, but only if it is before
848
        /// than the threshold value
849
        /// </summary>
850
        /// <param name="threshold"></param>
851
        /// <param name="cloudObjects"></param>
852
        /// <returns></returns>
853
        private static DateTime? GetLatestDateBefore(DateTime? threshold, IList<ObjectInfo> cloudObjects)
854
        {
855
            DateTime? maxDate = null;
856
            if (cloudObjects!=null &&  cloudObjects.Count > 0)
857
                maxDate = cloudObjects.Max(obj => obj.Last_Modified);
858
            if (maxDate == null || maxDate == DateTime.MinValue)
859
                return threshold;
860
            if (threshold == null || threshold == DateTime.MinValue || threshold > maxDate)
861
                return maxDate;
862
            return threshold;
863
        }
864

    
865
        /// <summary>
866
        /// Returns the latest LastModified date from the list of objects, but only if it is after
867
        /// the threshold value
868
        /// </summary>
869
        /// <param name="threshold"></param>
870
        /// <param name="cloudObjects"></param>
871
        /// <returns></returns>
872
        private static DateTime? GetLatestDateAfter(DateTime? threshold, IList<ObjectInfo> cloudObjects)
873
        {
874
            DateTime? maxDate = null;
875
            if (cloudObjects!=null &&  cloudObjects.Count > 0)
876
                maxDate = cloudObjects.Max(obj => obj.Last_Modified);
877
            if (maxDate == null || maxDate == DateTime.MinValue)
878
                return threshold;
879
            if (threshold == null || threshold == DateTime.MinValue || threshold < maxDate)
880
                return maxDate;
881
            return threshold;
882
        }
883

    
884
        readonly AccountsDifferencer _differencer = new AccountsDifferencer();
885
        private Dictionary<Uri, List<Uri>> _selectiveUris = new Dictionary<Uri, List<Uri>>();
886
        private bool _pause;
887
        private static string MERKLE_EMPTY = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
888

    
889
        /// <summary>
890
        /// Deletes local files that are not found in the list of cloud files
891
        /// </summary>
892
        /// <param name="accountInfo"></param>
893
        /// <param name="cloudFiles"></param>
894
        private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles)
895
        {
896
            if (accountInfo == null)
897
                throw new ArgumentNullException("accountInfo");
898
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
899
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
900
            if (cloudFiles == null)
901
                throw new ArgumentNullException("cloudFiles");
902
            Contract.EndContractBlock();
903

    
904
            var deletedFiles = new List<FileSystemInfo>();
905
            foreach (var objectInfo in cloudFiles)
906
            {
907
                if (Log.IsDebugEnabled)
908
                    Log.DebugFormat("Handle deleted [{0}]", objectInfo.Uri);
909
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
910
                var item = FileAgent.GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);
911
                if (Log.IsDebugEnabled)
912
                    Log.DebugFormat("Will delete [{0}] for [{1}]", item.FullName, objectInfo.Uri);
913
                if (item.Exists)
914
                {
915
                    if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
916
                    {
917
                        item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
918

    
919
                    }
920

    
921

    
922
                    Log.DebugFormat("Deleting {0}", item.FullName);
923

    
924
                    var directory = item as DirectoryInfo;
925
                    if (directory != null)
926
                        directory.Delete(true);
927
                    else
928
                        item.Delete();
929
                    Log.DebugFormat("Deleted [{0}] for [{1}]", item.FullName, objectInfo.Uri);
930
                    DateTime lastDate;
931
                    _lastSeen.TryRemove(item.FullName, out lastDate);
932
                    deletedFiles.Add(item);
933
                }
934
                StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted, "File Deleted");
935
            }
936
            Log.InfoFormat("[{0}] files were deleted", deletedFiles.Count);
937
            StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count),
938
                                              TraceLevel.Info);
939

    
940
        }
941

    
942
        private void MarkSuspectedDeletes(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles)
943
        {
944
//Only consider files that are not being modified, ie they are in the Unchanged state            
945
            var deleteCandidates = FileState.Queryable.Where(state =>
946
                                                             state.FilePath.StartsWith(accountInfo.AccountPath)
947
                                                             && state.FileStatus == FileStatus.Unchanged).ToList();
948

    
949

    
950
            //TODO: filesToDelete must take into account the Others container            
951
            var filesToDelete = (from deleteCandidate in deleteCandidates
952
                                 let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
953
                                 let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
954
                                 where
955
                                     !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)
956
                                 select localFile).ToList();
957

    
958

    
959
            //Set the status of missing files to Conflict
960
            foreach (var item in filesToDelete)
961
            {
962
                //Try to acquire a gate on the file, to take into account files that have been dequeued
963
                //and are being processed
964
                using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
965
                {
966
                    if (gate.Failed)
967
                        continue;
968
                    StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted,
969
                                              "Local file missing from server");
970
                }
971
            }
972
            UpdateStatus(PithosStatus.HasConflicts);
973
            StatusNotification.NotifyConflicts(filesToDelete,
974
                                               String.Format(
975
                                                   "{0} local files are missing from Pithos, possibly because they were deleted",
976
                                                   filesToDelete.Count));
977
            StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count),
978
                                              TraceLevel.Info);
979
        }
980

    
981
        private void ReportConflictForMismatch(string localFilePath)
982
        {
983
            if (String.IsNullOrWhiteSpace(localFilePath))
984
                throw new ArgumentNullException("localFilePath");
985
            Contract.EndContractBlock();
986

    
987
            StatusKeeper.SetFileState(localFilePath, FileStatus.Conflict, FileOverlayStatus.Conflict, "File changed at the server");
988
            UpdateStatus(PithosStatus.HasConflicts);
989
            var message = String.Format("Conflict detected for file {0}", localFilePath);
990
            Log.Warn(message);
991
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
992
        }
993

    
994

    
995

    
996
        /// <summary>
997
        /// Creates a Sync action for each changed server file
998
        /// </summary>
999
        /// <param name="accountInfo"></param>
1000
        /// <param name="changes"></param>
1001
        /// <returns></returns>
1002
        private IEnumerable<CloudAction> ChangesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> changes)
1003
        {
1004
            if (changes == null)
1005
                throw new ArgumentNullException();
1006
            Contract.EndContractBlock();
1007
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
1008

    
1009
            //In order to avoid multiple iterations over the files, we iterate only once
1010
            //over the remote files
1011
            foreach (var objectInfo in changes)
1012
            {
1013
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
1014
                //If a directory object already exists, we may need to sync it
1015
                if (fileAgent.Exists(relativePath))
1016
                {
1017
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
1018
                    //We don't need to sync directories
1019
                    if (objectInfo.IsDirectory && localFile is DirectoryInfo)
1020
                        continue;
1021
                    using (new SessionScope(FlushAction.Never))
1022
                    {
1023
                        var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
1024
                        _lastSeen[localFile.FullName] = DateTime.Now;
1025
                        //Common files should be checked on a per-case basis to detect differences, which is newer
1026

    
1027
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
1028
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
1029
                                                     accountInfo.BlockHash,"Poll Changes");
1030
                    }
1031
                }
1032
                else
1033
                {
1034
                    //Remote files should be downloaded
1035
                    yield return new CloudDownloadAction(accountInfo, objectInfo,"Poll Changes");
1036
                }
1037
            }
1038
        }
1039

    
1040
        /// <summary>
1041
        /// Creates a Local Move action for each moved server file
1042
        /// </summary>
1043
        /// <param name="accountInfo"></param>
1044
        /// <param name="moves"></param>
1045
        /// <returns></returns>
1046
        private IEnumerable<CloudAction> MovesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> moves)
1047
        {
1048
            if (moves == null)
1049
                throw new ArgumentNullException();
1050
            Contract.EndContractBlock();
1051
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
1052

    
1053
            //In order to avoid multiple iterations over the files, we iterate only once
1054
            //over the remote files
1055
            foreach (var objectInfo in moves)
1056
            {
1057
                var previousRelativepath = objectInfo.Previous.RelativeUrlToFilePath(accountInfo.UserName);
1058
                //If the previous file already exists, we can execute a Move operation
1059
                if (fileAgent.Exists(previousRelativepath))
1060
                {
1061
                    var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
1062
                    using (new SessionScope(FlushAction.Never))
1063
                    {
1064
                        var state = StatusKeeper.GetStateByFilePath(previousFile.FullName);
1065
                        _lastSeen[previousFile.FullName] = DateTime.Now;
1066

    
1067
                        //For each moved object we need to move both the local file and update                                                
1068
                        yield return new CloudAction(accountInfo, CloudActionType.RenameLocal,
1069
                                                     previousFile, objectInfo, state, accountInfo.BlockSize,
1070
                                                     accountInfo.BlockHash,"Poll Moves");
1071
                        //For modified files, we need to download the changes as well
1072
                        if (objectInfo.X_Object_Hash != objectInfo.PreviousHash)
1073
                            yield return new CloudDownloadAction(accountInfo,objectInfo, "Poll Moves");
1074
                    }
1075
                }
1076
                //If the previous file does not exist, we need to download it in the new location
1077
                else
1078
                {
1079
                    //Remote files should be downloaded
1080
                    yield return new CloudDownloadAction(accountInfo, objectInfo, "Poll Moves");
1081
                }
1082
            }
1083
        }
1084

    
1085

    
1086
        /// <summary>
1087
        /// Creates a download action for each new server file
1088
        /// </summary>
1089
        /// <param name="accountInfo"></param>
1090
        /// <param name="creates"></param>
1091
        /// <returns></returns>
1092
        private IEnumerable<CloudAction> CreatesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> creates)
1093
        {
1094
            if (creates == null)
1095
                throw new ArgumentNullException();
1096
            Contract.EndContractBlock();
1097
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
1098

    
1099
            //In order to avoid multiple iterations over the files, we iterate only once
1100
            //over the remote files
1101
            foreach (var objectInfo in creates)
1102
            {
1103
                if (Log.IsDebugEnabled)
1104
                    Log.DebugFormat("[NEW INFO] {0}",objectInfo.Uri);
1105

    
1106
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
1107

    
1108
                //If the object already exists, we should check before uploading or downloading
1109
                if (fileAgent.Exists(relativePath))
1110
                {
1111
                    var localFile= fileAgent.GetFileSystemInfo(relativePath);
1112
                    var state = StatusKeeper.GetStateByFilePath(localFile.WithProperCapitalization().FullName);
1113
                    yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
1114
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
1115
                                                     accountInfo.BlockHash,"Poll Creates");                    
1116
                }
1117
                else
1118
                {
1119
                    //Remote files should be downloaded
1120
                    yield return new CloudDownloadAction(accountInfo, objectInfo,"Poll Creates");
1121
                }
1122

    
1123
            }
1124
        }
1125

    
1126
        /// <summary>
1127
        /// Notify the UI to update the visual status
1128
        /// </summary>
1129
        /// <param name="status"></param>
1130
        private void UpdateStatus(PithosStatus status)
1131
        {
1132
            try
1133
            {
1134
                StatusNotification.SetPithosStatus(status);
1135
                //StatusNotification.Notify(new Notification());
1136
            }
1137
            catch (Exception exc)
1138
            {
1139
                //Failure is not critical, just log it
1140
                Log.Warn("Error while updating status", exc);
1141
            }
1142
        }
1143

    
1144
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
1145
        {
1146
            var containerPaths = from container in containers
1147
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
1148
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
1149
                                 select containerPath;
1150

    
1151
            foreach (var path in containerPaths)
1152
            {
1153
                Directory.CreateDirectory(path);
1154
            }
1155
        }
1156

    
1157
        public void AddAccount(AccountInfo accountInfo)
1158
        {
1159
            //Avoid adding a duplicate accountInfo
1160
            _accounts.TryAdd(accountInfo.AccountKey, accountInfo);
1161
        }
1162

    
1163
        public void RemoveAccount(AccountInfo accountInfo)
1164
        {
1165
            AccountInfo account;
1166
            _accounts.TryRemove(accountInfo.AccountKey, out account);
1167

    
1168
            SnapshotDifferencer differencer;
1169
            _differencer.Differencers.TryRemove(accountInfo.AccountKey, out differencer);
1170
        }
1171

    
1172
        public void SetSelectivePaths(AccountInfo accountInfo,Uri[] added, Uri[] removed)
1173
        {
1174
            AbortRemovedPaths(accountInfo,removed);
1175
            //DownloadNewPaths(accountInfo,added);
1176
        }
1177

    
1178
/*
1179
        private void DownloadNewPaths(AccountInfo accountInfo, Uri[] added)
1180
        {
1181
            var client = new CloudFilesClient(accountInfo);
1182
            foreach (var folderUri in added)
1183
            {
1184
                try
1185
                {
1186

    
1187
                    string account;
1188
                    string container;
1189
                    var segmentsCount = folderUri.Segments.Length;
1190
                    //Is this an account URL?
1191
                    if (segmentsCount < 3)
1192
                        continue;
1193
                    //Is this a container or  folder URL?
1194
                    if (segmentsCount == 3)
1195
                    {
1196
                        account = folderUri.Segments[1].TrimEnd('/');
1197
                        container = folderUri.Segments[2].TrimEnd('/');
1198
                    }
1199
                    else
1200
                    {
1201
                        account = folderUri.Segments[2].TrimEnd('/');
1202
                        container = folderUri.Segments[3].TrimEnd('/');
1203
                    }
1204
                    IList<ObjectInfo> items;
1205
                    if (segmentsCount > 3)
1206
                    {
1207
                        //List folder
1208
                        var folder = String.Join("", folderUri.Segments.Splice(4));
1209
                        items = client.ListObjects(account, container, folder);
1210
                    }
1211
                    else
1212
                    {
1213
                        //List container
1214
                        items = client.ListObjects(account, container);
1215
                    }
1216
                    var actions = CreatesToActions(accountInfo, items);
1217
                    foreach (var action in actions)
1218
                    {
1219
                        NetworkAgent.Post(action);
1220
                    }
1221
                }
1222
                catch (Exception exc)
1223
                {
1224
                    Log.WarnFormat("Listing of new selective path [{0}] failed with \r\n{1}", folderUri, exc);
1225
                }
1226
            }
1227

    
1228
            //Need to get a listing of each of the URLs, then post them to the NetworkAgent
1229
            //CreatesToActions(accountInfo,)
1230

    
1231
/*            NetworkAgent.Post();#1#
1232
        }
1233
*/
1234

    
1235
        private void AbortRemovedPaths(AccountInfo accountInfo, Uri[] removed)
1236
        {
1237
            /*this.NetworkAgent.*/
1238
        }
1239
    }
1240
}