Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 303596f9

History | View | Annotate | Download (65.2 kB)

1
// -----------------------------------------------------------------------
2
// <copyright file="NetworkAgent.cs" company="GRNET">
3
// Copyright 2011-2012 GRNET S.A. All rights reserved.
4
// 
5
// Redistribution and use in source and binary forms, with or
6
// without modification, are permitted provided that the following
7
// conditions are met:
8
// 
9
//   1. Redistributions of source code must retain the above
10
//      copyright notice, this list of conditions and the following
11
//      disclaimer.
12
// 
13
//   2. Redistributions in binary form must reproduce the above
14
//      copyright notice, this list of conditions and the following
15
//      disclaimer in the documentation and/or other materials
16
//      provided with the distribution.
17
// 
18
// THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
// POSSIBILITY OF SUCH DAMAGE.
30
// 
31
// The views and conclusions contained in the software and
32
// documentation are those of the authors and should not be
33
// interpreted as representing official policies, either expressed
34
// or implied, of GRNET S.A.
35
// </copyright>
36
// -----------------------------------------------------------------------
37

    
38
using System;
39
using System.Collections.Concurrent;
40
using System.Collections.Generic;
41
using System.ComponentModel.Composition;
42
using System.Diagnostics;
43
using System.Diagnostics.Contracts;
44
using System.IO;
45
using System.Linq;
46
using System.Net;
47
using System.Threading;
48
using System.Threading.Tasks;
49
using System.Threading.Tasks.Dataflow;
50
using Castle.ActiveRecord;
51
using Pithos.Interfaces;
52
using Pithos.Network;
53
using log4net;
54

    
55
namespace Pithos.Core.Agents
56
{
57
    //TODO: Ensure all network operations use exact casing. Pithos is case sensitive
58
    [Export]
59
    public class NetworkAgent
60
    {
61
        private Agent<CloudAction> _agent;
62

    
63
        //A separate agent is used to execute delete actions immediatelly;
64
        private ActionBlock<CloudDeleteAction> _deleteAgent;
65
        readonly ConcurrentDictionary<string,DateTime> _deletedFiles=new ConcurrentDictionary<string, DateTime>();
66

    
67

    
68

    
69
        [System.ComponentModel.Composition.Import]
70
        public IStatusKeeper StatusKeeper { get; set; }
71
        
72
        public IStatusNotification StatusNotification { get; set; }
73

    
74
        private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
75

    
76
        private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
77

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

    
81
        private bool _firstPoll = true;
82
        
83
        private TaskCompletionSource<bool> _tcs;
84
        private readonly AsyncManualResetEvent _pauseAgent = new AsyncManualResetEvent(true);
85

    
86
        private ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();
87

    
88
        public void Start()
89
        {
90
            _firstPoll = true;
91
            _agent = Agent<CloudAction>.Start(inbox =>
92
            {
93
                Action loop = null;
94
                loop = () =>
95
                {
96
                    _pauseAgent.Wait();
97
                    var message = inbox.Receive();
98
                    var process=message.Then(Process,inbox.CancellationToken);
99
                    inbox.LoopAsync(process, loop);
100
                };
101
                loop();
102
            });
103

    
104
            _deleteAgent = new ActionBlock<CloudDeleteAction>(message =>ProcessDelete(message),new ExecutionDataflowBlockOptions{MaxDegreeOfParallelism=4});
105
            /*
106
                Action loop = null;
107
                loop = () =>
108
                            {
109
                                var message = inbox.Receive();
110
                                var process = message.Then(ProcessDelete,inbox.CancellationToken);
111
                                inbox.LoopAsync(process, loop);
112
                            };
113
                loop();
114
*/
115

    
116
        }
117

    
118
        private async Task Process(CloudAction action)
119
        {
120
            if (action == null)
121
                throw new ArgumentNullException("action");
122
            if (action.AccountInfo==null)
123
                throw new ArgumentException("The action.AccountInfo is empty","action");
124
            Contract.EndContractBlock();
125

    
126
            UpdateStatus(PithosStatus.Syncing);
127
            var accountInfo = action.AccountInfo;
128

    
129
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
130
            {                
131
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
132

    
133
                var cloudFile = action.CloudFile;
134
                var downloadPath = action.GetDownloadPath();
135

    
136
                try
137
                {                    
138
                    if (action.Action == CloudActionType.DeleteCloud)
139
                    {                        
140
                        //Redirect deletes to the delete agent 
141
                        _deleteAgent.Post((CloudDeleteAction)action);
142
                    }
143
                    if (IsDeletedFile(action))
144
                    {
145
                        //Clear the status of already deleted files to avoid reprocessing
146
                        if (action.LocalFile != null)
147
                            this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
148
                    }
149
                    else
150
                    {
151
                        switch (action.Action)
152
                        {
153
                            case CloudActionType.UploadUnconditional:
154
                                //Abort if the file was deleted before we reached this point
155
                                await UploadCloudFile(action);
156
                                break;
157
                            case CloudActionType.DownloadUnconditional:
158
                                await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
159
                                break;
160
                            case CloudActionType.RenameCloud:
161
                                var moveAction = (CloudMoveAction)action;
162
                                RenameCloudFile(accountInfo, moveAction);
163
                                break;
164
                            case CloudActionType.MustSynch:
165
                                if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
166
                                {
167
                                    await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
168
                                }
169
                                else
170
                                {
171
                                    await SyncFiles(accountInfo, action);
172
                                }
173
                                break;
174
                        }
175
                    }
176
                    Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
177
                                           action.CloudFile.Name);
178
                }
179
                catch (WebException exc)
180
                {
181
                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
182
                }
183
                catch (OperationCanceledException)
184
                {
185
                    throw;
186
                }
187
                catch (DirectoryNotFoundException)
188
                {
189
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
190
                        action.Action, action.LocalFile, action.CloudFile);
191
                    //Post a delete action for the missing file
192
                    Post(new CloudDeleteAction(action));
193
                }
194
                catch (FileNotFoundException)
195
                {
196
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
197
                        action.Action, action.LocalFile, action.CloudFile);
198
                    //Post a delete action for the missing file
199
                    Post(new CloudDeleteAction(action));
200
                }
201
                catch (Exception exc)
202
                {
203
                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
204
                                     action.Action, action.LocalFile, action.CloudFile, exc);
205

    
206
                    _agent.Post(action);
207
                }
208
                finally
209
                {
210
                    UpdateStatus(PithosStatus.InSynch);                    
211
                }
212
            }
213
        }
214

    
215
        private void UpdateStatus(PithosStatus status)
216
        {
217
            StatusKeeper.SetPithosStatus(status);
218
            StatusNotification.Notify(new Notification());
219
        }
220

    
221
        /// <summary>
222
        /// Processes cloud delete actions
223
        /// </summary>
224
        /// <param name="action">The delete action to execute</param>
225
        /// <returns></returns>
226
        /// <remarks>
227
        /// When a file/folder is deleted locally, we must delete it ASAP from the server and block any download
228
        /// operations that may be in progress.
229
        /// <para>
230
        /// A separate agent is used to process deletes because the main agent may be busy with a long operation.
231
        /// </para>
232
        /// </remarks>
233
        private async Task ProcessDelete(CloudDeleteAction action)
234
        {
235
            if (action == null)
236
                throw new ArgumentNullException("action");
237
            if (action.AccountInfo==null)
238
                throw new ArgumentException("The action.AccountInfo is empty","action");
239
            Contract.EndContractBlock();
240

    
241
            var accountInfo = action.AccountInfo;
242

    
243
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
244
            {                
245
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
246

    
247
                var cloudFile = action.CloudFile;
248

    
249
                try
250
                {
251
                    //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
252
                    //agent
253
                    using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
254
                    {
255

    
256
                        //Add the file URL to the deleted files list
257
                        var key = GetFileKey(action.CloudFile);
258
                        _deletedFiles[key] = DateTime.Now;
259

    
260
                        _pauseAgent.Reset();
261
                        // and then delete the file from the server
262
                                DeleteCloudFile(accountInfo, cloudFile);
263

    
264
                        Log.InfoFormat("[ACTION] End Delete {0}:{1}->{2}", action.Action, action.LocalFile,
265
                                       action.CloudFile.Name);
266
                    }
267
                }
268
                catch (WebException exc)
269
                {
270
                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
271
                }
272
                catch (OperationCanceledException)
273
                {
274
                    throw;
275
                }
276
                catch (DirectoryNotFoundException)
277
                {
278
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
279
                        action.Action, action.LocalFile, action.CloudFile);
280
                    //Repost a delete action for the missing file
281
                    _deleteAgent.Post(action);
282
                }
283
                catch (FileNotFoundException)
284
                {
285
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
286
                        action.Action, action.LocalFile, action.CloudFile);
287
                    //Post a delete action for the missing file
288
                    _deleteAgent.Post(action);
289
                }
290
                catch (Exception exc)
291
                {
292
                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
293
                                     action.Action, action.LocalFile, action.CloudFile, exc);
294

    
295
                    _deleteAgent.Post(action);
296
                }
297
                finally
298
                {
299
                    //Set the event when all delete actions are processed
300
                    if (_deleteAgent.InputCount == 0)
301
                        _pauseAgent.Set();
302

    
303
                }
304
            }
305
        }
306

    
307
        private static string GetFileKey(ObjectInfo info)
308
        {
309
            var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
310
            return key;
311
        }
312

    
313
        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
314
        {
315
            if (accountInfo == null)
316
                throw new ArgumentNullException("accountInfo");
317
            if (action==null)
318
                throw new ArgumentNullException("action");
319
            if (action.LocalFile==null)
320
                throw new ArgumentException("The action's local file is not specified","action");
321
            if (!Path.IsPathRooted(action.LocalFile.FullName))
322
                throw new ArgumentException("The action's local file path must be absolute","action");
323
            if (action.CloudFile== null)
324
                throw new ArgumentException("The action's cloud file is not specified", "action");
325
            Contract.EndContractBlock();
326

    
327
            var localFile = action.LocalFile;
328
            var cloudFile = action.CloudFile;
329
            var downloadPath=action.LocalFile.GetProperCapitalization();
330

    
331
            var cloudHash = cloudFile.Hash.ToLower();
332
            var localHash = action.LocalHash.Value.ToLower();
333
            var topHash = action.TopHash.Value.ToLower();
334

    
335
            //Not enough to compare only the local hashes, also have to compare the tophashes
336
            
337
            //If any of the hashes match, we are done
338
            if ((cloudHash == localHash || cloudHash == topHash))
339
            {
340
                Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
341
                return;
342
            }
343

    
344
            //The hashes DON'T match. We need to sync
345
            var lastLocalTime = localFile.LastWriteTime;
346
            var lastUpTime = cloudFile.Last_Modified;
347
            
348
            //If the local file is newer upload it
349
            if (lastUpTime <= lastLocalTime)
350
            {
351
                //It probably means it was changed while the app was down                        
352
                UploadCloudFile(action);
353
            }
354
            else
355
            {
356
                //It the cloud file has a later date, it was modified by another user or computer.
357
                //We need to check the local file's status                
358
                var status = StatusKeeper.GetFileStatus(downloadPath);
359
                switch (status)
360
                {
361
                    case FileStatus.Unchanged:                        
362
                        //If the local file's status is Unchanged, we can go on and download the newer cloud file
363
                        await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
364
                        break;
365
                    case FileStatus.Modified:
366
                        //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
367
                        //We can't ensure that a file modified online since the last time will appear as Modified, unless we 
368
                        //index all files before we start listening.                       
369
                    case FileStatus.Created:
370
                        //If the local file is Created, it means that the local and cloud files aren't related,
371
                        // yet they have the same name.
372

    
373
                        //In both cases we must mark the file as in conflict
374
                        ReportConflict(downloadPath);
375
                        break;
376
                    default:
377
                        //Other cases should never occur. Mark them as Conflict as well but log a warning
378
                        ReportConflict(downloadPath);
379
                        Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
380
                                       downloadPath, action.CloudFile.Name);
381
                        break;
382
                }
383
            }
384
        }
385

    
386
        private void ReportConflict(string downloadPath)
387
        {
388
            if (String.IsNullOrWhiteSpace(downloadPath))
389
                throw new ArgumentNullException("downloadPath");
390
            Contract.EndContractBlock();
391

    
392
            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
393
            UpdateStatus(PithosStatus.HasConflicts);
394
            var message = String.Format("Conflict detected for file {0}", downloadPath);
395
            Log.Warn(message);
396
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
397
        }
398

    
399
        public void Post(CloudAction cloudAction)
400
        {
401
            if (cloudAction == null)
402
                throw new ArgumentNullException("cloudAction");
403
            if (cloudAction.AccountInfo==null)
404
                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
405
            Contract.EndContractBlock();
406

    
407
            _pauseAgent.Wait();
408

    
409
            //If the action targets a local file, add a treehash calculation
410
            if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
411
            {
412
                var accountInfo = cloudAction.AccountInfo;
413
                var localFile = (FileInfo) cloudAction.LocalFile;
414
                if (localFile.Length > accountInfo.BlockSize)
415
                    cloudAction.TopHash =
416
                        new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
417
                                                                                accountInfo.BlockSize,
418
                                                                                accountInfo.BlockHash, Settings.HashingParallelism).Result
419
                                                    .TopHash.ToHashString());
420
                else
421
                {
422
                    cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
423
                }
424
            }
425
            else
426
            {
427
                //The hash for a directory is the empty string
428
                cloudAction.TopHash = new Lazy<string>(() => String.Empty);
429
            }
430
            
431
            if (cloudAction is CloudDeleteAction)
432
                _deleteAgent.Post((CloudDeleteAction)cloudAction);
433
            else
434
                _agent.Post(cloudAction);
435
        }
436

    
437
       /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
438
        {
439
            public bool Equals(ObjectInfo x, ObjectInfo y)
440
            {
441
                return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
442
            }
443

    
444
            public int GetHashCode(ObjectInfo obj)
445
            {
446
                return obj.Name.ToLower().GetHashCode();
447
            }
448
        }*/
449

    
450
        public void SynchNow()
451
        {             
452
            if (_tcs!=null)
453
                _tcs.TrySetResult(true);
454
            else
455
            {
456
                //TODO: This may be OK for testing purposes, but we have no guarantee that it will
457
                //work properly in production
458
                PollRemoteFiles(repeat:false);
459
            }
460
        }
461

    
462
        //Remote files are polled periodically. Any changes are processed
463
        public async Task PollRemoteFiles(DateTime? since = null,bool repeat=true)
464
        {
465
            UpdateStatus(PithosStatus.Syncing);
466
            StatusNotification.Notify(new PollNotification());
467

    
468
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
469
            {
470
                //If this poll fails, we will retry with the same since value
471
                var nextSince = since;
472
                try
473
                {
474
                    //Next time we will check for all changes since the current check minus 1 second
475
                    //This is done to ensure there are no discrepancies due to clock differences
476
                    DateTime current = DateTime.Now.AddSeconds(-1);
477

    
478
                    var tasks = from accountInfo in _accounts
479
                                select ProcessAccountFiles(accountInfo, since);
480

    
481
                    await TaskEx.WhenAll(tasks.ToList());
482
                                        
483
                    _firstPoll = false;
484
                    //Reschedule the poll with the current timestamp as a "since" value
485
                    if (repeat)
486
                        nextSince = current;
487
                    else
488
                        return;
489
                }
490
                catch (Exception ex)
491
                {
492
                    Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
493
                    //In case of failure retry with the same "since" value
494
                }
495
                
496
                UpdateStatus(PithosStatus.InSynch);
497
                //Wait for the polling interval to pass or the Manual flat to be toggled
498
                nextSince = await WaitForScheduledOrManualPoll(nextSince);
499

    
500
                PollRemoteFiles(nextSince);
501

    
502
            }
503
        }
504

    
505
        private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
506
        {            
507
            _tcs = new TaskCompletionSource<bool>();
508
            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
509
            var signaledTask = await TaskEx.WhenAny(_tcs.Task, wait);
510
            //If polling is signalled by SynchNow, ignore the since tag
511
            if (signaledTask is Task<bool>)
512
                return null;
513
            return since;
514
        }
515

    
516
        public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
517
        {   
518
            if (accountInfo==null)
519
                throw new ArgumentNullException("accountInfo");
520
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
521
                throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
522
            Contract.EndContractBlock();
523

    
524

    
525
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
526
            {
527
                await _pauseAgent.WaitAsync();
528

    
529
                Log.Info("Scheduled");
530
                var client = new CloudFilesClient(accountInfo)
531
                                 {
532
                                     Proxy = PithosMonitor.ProxyFromSettings(this.Settings)
533
                                 };
534

    
535
                var containers = client.ListContainers(accountInfo.UserName);
536

    
537

    
538
                CreateContainerFolders(accountInfo, containers);
539

    
540
                try
541
                {
542
                    await _pauseAgent.WaitAsync();
543
                    //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
544
                    //than delete a file that was created while we were executing the poll                    
545
                    var pollTime = DateTime.Now;
546
                    
547
                    //Get the list of server objects changed since the last check
548
                    //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
549
                    var listObjects = (from container in containers
550
                                      select  Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
551
                                            client.ListObjects(accountInfo.UserName,container.Name, since),container.Name)).ToList();
552

    
553
                    var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => client.ListSharedObjects(since), "shared");
554
                    listObjects.Add(listShared);
555
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
556

    
557
                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
558
                    {
559
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
560

    
561
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
562
                        var remoteObjects = from objectList in listTasks
563
                                            where (string) objectList.AsyncState != "trash"
564
                                            from obj in objectList.Result
565
                                            select obj;
566

    
567
                        //TODO: Change the way deleted objects are detected.
568
                        //The list operation returns all existing objects so we could detect deleted remote objects
569
                        //by detecting objects that exist only locally. There are several cases where this is NOT the case:
570
                        //1.    The first time the application runs, as there may be files that were added while 
571
                        //      the application was down.
572
                        //2.    An object that is currently being uploaded will not appear in the remote list
573
                        //      until the upload finishes.
574
                        //      SOLUTION 1: Check the upload/download queue for the file
575
                        //      SOLUTION 2: Check the SQLite states for the file's entry. If it is being uploaded, 
576
                        //          or its last modification was after the current poll, don't delete it. This way we don't
577
                        //          delete objects whose upload finished too late to be included in the list.
578
                        //We need to detect and protect against such situations
579
                        //TODO: Does FileState have a LastModification field?
580
                        //TODO: How do we update the LastModification field? Do we need to add SQLite triggers?
581
                        //      Do we need to use a proper SQLite schema?
582
                        //      We can create a trigger with 
583
                        // CREATE TRIGGER IF NOT EXISTS update_last_modified UPDATE ON FileState FOR EACH ROW
584
                        //  BEGIN
585
                        //      UPDATE FileState SET LastModification=datetime('now')  WHERE Id=old.Id;
586
                        //  END;
587
                        //
588
                        //NOTE: Some files may have been deleted remotely while the application was down. 
589
                        //  We DO have to delete those files. Checking the trash makes it easy to detect them,
590
                        //  Otherwise, we can't be really sure whether we need to upload or delete 
591
                        //  the local-only files.
592
                        //  SOLUTION 1: Ask the user when such a local-only file is detected during the first poll.
593
                        //  SOLUTION 2: Mark conflict and ask the user as in #1
594

    
595
                        var trashObjects = dict["trash"].Result;
596
                        var sharedObjects = dict["shared"].Result;
597

    
598
                        //Items with the same name, hash may be both in the container and the trash
599
                        //Don't delete items that exist in the container
600
                        var realTrash = from trash in trashObjects
601
                                        where
602
                                            !remoteObjects.Any(
603
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
604
                                        select trash;
605
                        ProcessTrashedFiles(accountInfo, realTrash);
606

    
607

    
608
                        var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
609
                                     let name = info.Name
610
                                     where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
611
                                           !name.StartsWith(FolderConstants.CacheFolder + "/",
612
                                                            StringComparison.InvariantCultureIgnoreCase)
613
                                     select info).ToList();
614

    
615
                        var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);
616
                        
617
                        ProcessDeletedFiles(accountInfo, differencer.Deleted, pollTime);
618

    
619
                        //Create a list of actions from the remote files
620
                        var allActions = ChangesToActions(accountInfo, differencer.Changed)
621
                                        .Union(
622
                                        CreatesToActions(accountInfo,differencer.Created));
623

    
624
                        
625
                        //var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
626

    
627
                        //And remove those that are already being processed by the agent
628
                        var distinctActions = allActions
629
                            .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
630
                            .ToList();
631

    
632
                        //Queue all the actions
633
                        foreach (var message in distinctActions)
634
                        {
635
                            Post(message);
636
                        }
637

    
638
                        Log.Info("[LISTENER] End Processing");
639
                    }
640
                }
641
                catch (Exception ex)
642
                {
643
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
644
                    return;
645
                }
646

    
647
                Log.Info("[LISTENER] Finished");
648

    
649
            }
650
        }
651

    
652
        AccountsDifferencer _differencer= new AccountsDifferencer();
653

    
654
/*
655
        Dictionary<string, List<ObjectInfo>> _currentSnapshot = new Dictionary<string, List<ObjectInfo>>();
656
        Dictionary<string, List<ObjectInfo>> _previousSnapshot = new Dictionary<string, List<ObjectInfo>>();
657
*/
658

    
659
        /// <summary>
660
        /// Deletes local files that are not found in the list of cloud files
661
        /// </summary>
662
        /// <param name="accountInfo"></param>
663
        /// <param name="cloudFiles"></param>
664
        /// <param name="pollTime"></param>
665
        private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
666
        {
667
            if (accountInfo == null)
668
                throw new ArgumentNullException("accountInfo");
669
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
670
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
671
            if (cloudFiles == null)
672
                throw new ArgumentNullException("cloudFiles");
673
            Contract.EndContractBlock();
674

    
675
            //On the first run
676
            if (_firstPoll)
677
            {
678
                //Only consider files that are not being modified, ie they are in the Unchanged state            
679
                var deleteCandidates = FileState.Queryable.Where(state =>
680
                    state.FilePath.StartsWith(accountInfo.AccountPath)
681
                    && state.FileStatus == FileStatus.Unchanged).ToList();
682

    
683

    
684
                //TODO: filesToDelete must take into account the Others container            
685
                var filesToDelete = (from deleteCandidate in deleteCandidates
686
                                         let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
687
                                         let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
688
                                     where
689
                                         !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)
690
                                     select localFile).ToList();
691
            
692

    
693

    
694
                //Set the status of missing files to Conflict
695
                foreach (var item in filesToDelete)
696
                {
697
                    //Try to acquire a gate on the file, to take into account files that have been dequeued
698
                    //and are being processed
699
                    using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
700
                    {
701
                        if (gate.Failed)
702
                            continue;
703
                        StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);
704
                    }
705
                }
706
                UpdateStatus(PithosStatus.HasConflicts);
707
                StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted",filesToDelete.Count));
708
                StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count), TraceLevel.Info);
709
            }
710
            else
711
            {
712
                var deletedFiles = new List<FileSystemInfo>();
713
                foreach (var objectInfo in cloudFiles)
714
                {
715
                    var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
716
                    var item = GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);
717
                    if (item.Exists)
718
                    {
719
                        //Try to acquire a gate on the file, to take into account files that have been dequeued
720
                        //and are being processed
721
                        //TODO: The gate is not enough. Perhaps we need to keep a journal of processed files and check against
722
                        //that as well.
723
/*
724
                        using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
725
                        {
726
                            if (gate.Failed)
727
                                continue;
728
*/
729
                            if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
730
                            {
731
                                item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
732

    
733
                            }
734
                            item.Delete();
735
                            DateTime lastDate;
736
                            _lastSeen.TryRemove(item.FullName, out lastDate);
737
                            deletedFiles.Add(item);
738
/*
739
                        }
740
*/
741
                    }
742
                    StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted);                    
743
                }
744
                StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count), TraceLevel.Info);
745
            }
746

    
747
        }
748

    
749
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
750
        {
751
            var containerPaths = from container in containers
752
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
753
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
754
                                 select containerPath;
755

    
756
            foreach (var path in containerPaths)
757
            {
758
                Directory.CreateDirectory(path);
759
            }
760
        }
761

    
762
        //Creates an appropriate action for each server file
763
        private IEnumerable<CloudAction> ChangesToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> changes)
764
        {
765
            if (changes==null)
766
                throw new ArgumentNullException();
767
            Contract.EndContractBlock();
768
            var fileAgent = GetFileAgent(accountInfo);
769

    
770
            //In order to avoid multiple iterations over the files, we iterate only once
771
            //over the remote files
772
            foreach (var objectInfo in changes)
773
            {
774
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
775
                //and remove any matching objects from the list, adding them to the commonObjects list
776
                if (fileAgent.Exists(relativePath))
777
                {
778
                    //If a directory object already exists, we don't need to perform any other action                    
779
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
780
                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
781
                        continue;
782
                    using (new SessionScope(FlushAction.Never))
783
                    {
784
                        var state =  StatusKeeper.GetStateByFilePath(localFile.FullName);
785
                        _lastSeen[localFile.FullName] = DateTime.Now;
786
                        //FileState.FindByFilePath(localFile.FullName);
787
                        //Common files should be checked on a per-case basis to detect differences, which is newer
788

    
789
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
790
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
791
                                                     accountInfo.BlockHash);
792
                    }
793
                }
794
                else
795
                {
796
                    //Remote files should be downloaded
797
                    yield return new CloudDownloadAction(accountInfo,objectInfo);
798
                }
799
            }            
800
        }
801

    
802
        private IEnumerable<CloudAction> CreatesToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> creates)
803
        {
804
            if (creates==null)
805
                throw new ArgumentNullException();
806
            Contract.EndContractBlock();
807
            var fileAgent = GetFileAgent(accountInfo);
808

    
809
            //In order to avoid multiple iterations over the files, we iterate only once
810
            //over the remote files
811
            foreach (var objectInfo in creates)
812
            {
813
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
814
                //and remove any matching objects from the list, adding them to the commonObjects list
815
                if (fileAgent.Exists(relativePath))
816
                {
817
                    //If the object already exists, we probably have a conflict
818
                    //If a directory object already exists, we don't need to perform any other action                    
819
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
820
                    StatusKeeper.SetFileState(localFile.FullName,FileStatus.Conflict,FileOverlayStatus.Conflict);
821
                }
822
                else
823
                {
824
                    //Remote files should be downloaded
825
                    yield return new CloudDownloadAction(accountInfo,objectInfo);
826
                }
827
            }            
828
        }
829

    
830
        //Creates an appropriate action for each server file
831
/*
832
        private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
833
        {
834
            if (remote==null)
835
                throw new ArgumentNullException();
836
            Contract.EndContractBlock();
837
            var fileAgent = GetFileAgent(accountInfo);
838

    
839
            //In order to avoid multiple iterations over the files, we iterate only once
840
            //over the remote files
841
            foreach (var objectInfo in remote)
842
            {
843
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
844
                //and remove any matching objects from the list, adding them to the commonObjects list
845
                
846
                if (fileAgent.Exists(relativePath))
847
                {
848
                    //If a directory object already exists, we don't need to perform any other action                    
849
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
850
                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
851
                        continue;
852
                    using (new SessionScope(FlushAction.Never))
853
                    {
854
                        var state =  StatusKeeper.GetStateByFilePath(localFile.FullName);
855
                        _lastSeen[localFile.FullName] = DateTime.Now;
856
                        //FileState.FindByFilePath(localFile.FullName);
857
                        //Common files should be checked on a per-case basis to detect differences, which is newer
858

    
859
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
860
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
861
                                                     accountInfo.BlockHash);
862
                    }
863
                }
864
                else
865
                {
866
                    //If there is no match we add them to the localFiles list
867
                    //but only if the file is not marked for deletion
868
                    var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
869
                    var fileStatus = StatusKeeper.GetFileStatus(targetFile);
870
                    if (fileStatus != FileStatus.Deleted)
871
                    {
872
                        //Remote files should be downloaded
873
                        yield return new CloudDownloadAction(accountInfo,objectInfo);
874
                    }
875
                }
876
            }            
877
        }
878
*/
879

    
880
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
881
        {
882
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
883
        }
884

    
885
        private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
886
        {
887
            var fileAgent = GetFileAgent(accountInfo);
888
            foreach (var trashObject in trashObjects)
889
            {
890
                var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
891
                //HACK: Assume only the "pithos" container is used. Must find out what happens when
892
                //deleting a file from a different container
893
                var relativePath = Path.Combine("pithos", barePath);
894
                fileAgent.Delete(relativePath);                                
895
            }
896
        }
897

    
898

    
899
        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
900
        {
901
            if (accountInfo==null)
902
                throw new ArgumentNullException("accountInfo");
903
            if (action==null)
904
                throw new ArgumentNullException("action");
905
            if (action.CloudFile==null)
906
                throw new ArgumentException("CloudFile","action");
907
            if (action.LocalFile==null)
908
                throw new ArgumentException("LocalFile","action");
909
            if (action.OldLocalFile==null)
910
                throw new ArgumentException("OldLocalFile","action");
911
            if (action.OldCloudFile==null)
912
                throw new ArgumentException("OldCloudFile","action");
913
            Contract.EndContractBlock();
914
            
915
            
916
            var newFilePath = action.LocalFile.FullName;
917
            
918
            //How do we handle concurrent renames and deletes/uploads/downloads?
919
            //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
920
            //  This should never happen as the network agent executes only one action at a time
921
            //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
922
            //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
923
            //  same name will fail.
924
            //  This should never happen as the network agent executes only one action at a time.
925
            //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
926
            //  to remove the rename from the queue.
927
            //  We can probably ignore this case. It will result in an error which should be ignored            
928

    
929
            
930
            //The local file is already renamed
931
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
932

    
933

    
934
            var account = action.CloudFile.Account ?? accountInfo.UserName;
935
            var container = action.CloudFile.Container;
936
            
937
            var client = new CloudFilesClient(accountInfo);
938
            //TODO: What code is returned when the source file doesn't exist?
939
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
940

    
941
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
942
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
943
            NativeMethods.RaiseChangeNotification(newFilePath);
944
        }
945

    
946
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
947
        {
948
            if (accountInfo == null)
949
                throw new ArgumentNullException("accountInfo");
950
            if (cloudFile==null)
951
                throw new ArgumentNullException("cloudFile");
952

    
953
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
954
                throw new ArgumentException("Invalid container", "cloudFile");
955
            Contract.EndContractBlock();
956
            
957
            var fileAgent = GetFileAgent(accountInfo);
958

    
959
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
960
            {
961
                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
962
                var info = fileAgent.GetFileSystemInfo(fileName);                
963
                var fullPath = info.FullName.ToLower();
964

    
965
                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
966

    
967
                var account = cloudFile.Account ?? accountInfo.UserName;
968
                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
969

    
970
                var client = new CloudFilesClient(accountInfo);
971
                client.DeleteObject(account, container, cloudFile.Name);
972

    
973
                StatusKeeper.ClearFileStatus(fullPath);
974
            }
975
        }
976

    
977
        //Download a file.
978
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
979
        {
980
            if (accountInfo == null)
981
                throw new ArgumentNullException("accountInfo");
982
            if (cloudFile == null)
983
                throw new ArgumentNullException("cloudFile");
984
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
985
                throw new ArgumentNullException("cloudFile");
986
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
987
                throw new ArgumentNullException("cloudFile");
988
            if (String.IsNullOrWhiteSpace(filePath))
989
                throw new ArgumentNullException("filePath");
990
            if (!Path.IsPathRooted(filePath))
991
                throw new ArgumentException("The filePath must be rooted", "filePath");
992
            Contract.EndContractBlock();
993
            
994

    
995
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
996
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
997

    
998
            var url = relativeUrl.ToString();
999
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
1000
                return;
1001

    
1002

    
1003
            //Are we already downloading or uploading the file? 
1004
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
1005
            {
1006
                if (gate.Failed)
1007
                    return;
1008
                //The file's hashmap will be stored in the same location with the extension .hashmap
1009
                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
1010
                
1011
                var client = new CloudFilesClient(accountInfo);
1012
                var account = cloudFile.Account;
1013
                var container = cloudFile.Container;
1014

    
1015
                if (cloudFile.Content_Type == @"application/directory")
1016
                {
1017
                    if (!Directory.Exists(localPath))
1018
                        Directory.CreateDirectory(localPath);
1019
                }
1020
                else
1021
                {                    
1022
                    //Retrieve the hashmap from the server
1023
                    var serverHash = await client.GetHashMap(account, container, url);
1024
                    //If it's a small file
1025
                    if (serverHash.Hashes.Count == 1)
1026
                        //Download it in one go
1027
                        await
1028
                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
1029
                        //Otherwise download it block by block
1030
                    else
1031
                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
1032

    
1033
                    if (cloudFile.AllowedTo == "read")
1034
                    {
1035
                        var attributes = File.GetAttributes(localPath);
1036
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
1037
                    }
1038
                }
1039

    
1040
                //Now we can store the object's metadata without worrying about ghost status entries
1041
                StatusKeeper.StoreInfo(localPath, cloudFile);
1042
                
1043
            }
1044
        }
1045

    
1046
        //Download a small file with a single GET operation
1047
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
1048
        {
1049
            if (client == null)
1050
                throw new ArgumentNullException("client");
1051
            if (cloudFile==null)
1052
                throw new ArgumentNullException("cloudFile");
1053
            if (relativeUrl == null)
1054
                throw new ArgumentNullException("relativeUrl");
1055
            if (String.IsNullOrWhiteSpace(filePath))
1056
                throw new ArgumentNullException("filePath");
1057
            if (!Path.IsPathRooted(filePath))
1058
                throw new ArgumentException("The localPath must be rooted", "filePath");
1059
            Contract.EndContractBlock();
1060

    
1061
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
1062
            //If the file already exists
1063
            if (File.Exists(localPath))
1064
            {
1065
                //First check with MD5 as this is a small file
1066
                var localMD5 = Signature.CalculateMD5(localPath);
1067
                var cloudHash=serverHash.TopHash.ToHashString();
1068
                if (localMD5==cloudHash)
1069
                    return;
1070
                //Then check with a treehash
1071
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
1072
                var localHash = localTreeHash.TopHash.ToHashString();
1073
                if (localHash==cloudHash)
1074
                    return;
1075
            }
1076
            StatusNotification.Notify(new CloudNotification { Data = cloudFile });
1077

    
1078
            var fileAgent = GetFileAgent(accountInfo);
1079
            //Calculate the relative file path for the new file
1080
            var relativePath = relativeUrl.RelativeUriToFilePath();
1081
            //The file will be stored in a temporary location while downloading with an extension .download
1082
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
1083
            //Make sure the target folder exists. DownloadFileTask will not create the folder
1084
            var tempFolder = Path.GetDirectoryName(tempPath);
1085
            if (!Directory.Exists(tempFolder))
1086
                Directory.CreateDirectory(tempFolder);
1087

    
1088
            //Download the object to the temporary location
1089
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
1090

    
1091
            //Create the local folder if it doesn't exist (necessary for shared objects)
1092
            var localFolder = Path.GetDirectoryName(localPath);
1093
            if (!Directory.Exists(localFolder))
1094
                Directory.CreateDirectory(localFolder);            
1095
            //And move it to its actual location once downloading is finished
1096
            if (File.Exists(localPath))
1097
                File.Replace(tempPath,localPath,null,true);
1098
            else
1099
                File.Move(tempPath,localPath);
1100
            //Notify listeners that a local file has changed
1101
            StatusNotification.NotifyChangedFile(localPath);
1102

    
1103
                       
1104
        }
1105

    
1106
        //Download a file asynchronously using blocks
1107
        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
1108
        {
1109
            if (client == null)
1110
                throw new ArgumentNullException("client");
1111
            if (cloudFile == null)
1112
                throw new ArgumentNullException("cloudFile");
1113
            if (relativeUrl == null)
1114
                throw new ArgumentNullException("relativeUrl");
1115
            if (String.IsNullOrWhiteSpace(filePath))
1116
                throw new ArgumentNullException("filePath");
1117
            if (!Path.IsPathRooted(filePath))
1118
                throw new ArgumentException("The filePath must be rooted", "filePath");
1119
            if (serverHash == null)
1120
                throw new ArgumentNullException("serverHash");
1121
            Contract.EndContractBlock();
1122
            
1123
           var fileAgent = GetFileAgent(accountInfo);
1124
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
1125
            
1126
            //Calculate the relative file path for the new file
1127
            var relativePath = relativeUrl.RelativeUriToFilePath();
1128
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
1129

    
1130
            
1131
                        
1132
            //Calculate the file's treehash
1133
            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
1134
                
1135
            //And compare it with the server's hash
1136
            var upHashes = serverHash.GetHashesAsStrings();
1137
            var localHashes = treeHash.HashDictionary;
1138
            for (int i = 0; i < upHashes.Length; i++)
1139
            {
1140
                //For every non-matching hash
1141
                var upHash = upHashes[i];
1142
                if (!localHashes.ContainsKey(upHash))
1143
                {
1144
                    StatusNotification.Notify(new CloudNotification { Data = cloudFile });
1145

    
1146
                    if (blockUpdater.UseOrphan(i, upHash))
1147
                    {
1148
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
1149
                        continue;
1150
                    }
1151
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
1152
                    var start = i*serverHash.BlockSize;
1153
                    //To download the last block just pass a null for the end of the range
1154
                    long? end = null;
1155
                    if (i < upHashes.Length - 1 )
1156
                        end= ((i + 1)*serverHash.BlockSize) ;
1157
                            
1158
                    //Download the missing block
1159
                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
1160

    
1161
                    //and store it
1162
                    blockUpdater.StoreBlock(i, block);
1163

    
1164

    
1165
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
1166
                }
1167
            }
1168

    
1169
            //Want to avoid notifications if no changes were made
1170
            var hasChanges = blockUpdater.HasBlocks;
1171
            blockUpdater.Commit();
1172
            
1173
            if (hasChanges)
1174
                //Notify listeners that a local file has changed
1175
                StatusNotification.NotifyChangedFile(localPath);
1176

    
1177
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
1178
        }
1179

    
1180

    
1181
        private async Task UploadCloudFile(CloudAction action)
1182
        {
1183
            if (action == null)
1184
                throw new ArgumentNullException("action");           
1185
            Contract.EndContractBlock();
1186

    
1187
            try
1188
            {                
1189
                var accountInfo = action.AccountInfo;
1190

    
1191
                var fileInfo = action.LocalFile;
1192

    
1193
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
1194
                    return;
1195
                
1196
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
1197
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
1198
                {
1199
                    var parts = relativePath.Split('\\');
1200
                    var accountName = parts[1];
1201
                    var oldName = accountInfo.UserName;
1202
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
1203
                    var nameIndex = absoluteUri.IndexOf(oldName);
1204
                    var root = absoluteUri.Substring(0, nameIndex);
1205

    
1206
                    accountInfo = new AccountInfo
1207
                    {
1208
                        UserName = accountName,
1209
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
1210
                        StorageUri = new Uri(root + accountName),
1211
                        BlockHash = accountInfo.BlockHash,
1212
                        BlockSize = accountInfo.BlockSize,
1213
                        Token = accountInfo.Token
1214
                    };
1215
                }
1216

    
1217

    
1218
                var fullFileName = fileInfo.GetProperCapitalization();
1219
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
1220
                {
1221
                    //Abort if the file is already being uploaded or downloaded
1222
                    if (gate.Failed)
1223
                        return;
1224

    
1225
                    var cloudFile = action.CloudFile;
1226
                    var account = cloudFile.Account ?? accountInfo.UserName;
1227

    
1228
                    var client = new CloudFilesClient(accountInfo);                    
1229
                    //Even if GetObjectInfo times out, we can proceed with the upload            
1230
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
1231

    
1232
                    //If this is a read-only file, do not upload changes
1233
                    if (info.AllowedTo == "read")
1234
                        return;
1235
                    
1236
                    //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
1237
                    if (fileInfo is DirectoryInfo)
1238
                    {
1239
                        //If the directory doesn't exist the Hash property will be empty
1240
                        if (String.IsNullOrWhiteSpace(info.Hash))
1241
                            //Go on and create the directory
1242
                            await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
1243
                    }
1244
                    else
1245
                    {
1246

    
1247
                        var cloudHash = info.Hash.ToLower();
1248

    
1249
                        var hash = action.LocalHash.Value;
1250
                        var topHash = action.TopHash.Value;
1251

    
1252
                        //If the file hashes match, abort the upload
1253
                        if (hash == cloudHash || topHash == cloudHash)
1254
                        {
1255
                            //but store any metadata changes 
1256
                            StatusKeeper.StoreInfo(fullFileName, info);
1257
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1258
                            return;
1259
                        }
1260

    
1261

    
1262
                        //Mark the file as modified while we upload it
1263
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1264
                        //And then upload it
1265

    
1266
                        //Upload even small files using the Hashmap. The server may already contain
1267
                        //the relevant block
1268

    
1269
                        //First, calculate the tree hash
1270
                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1271
                                                                              accountInfo.BlockHash, 2);
1272

    
1273
                        await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1274
                    }
1275
                    //If everything succeeds, change the file and overlay status to normal
1276
                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1277
                }
1278
                //Notify the Shell to update the overlays
1279
                NativeMethods.RaiseChangeNotification(fullFileName);
1280
                StatusNotification.NotifyChangedFile(fullFileName);
1281
            }
1282
            catch (AggregateException ex)
1283
            {
1284
                var exc = ex.InnerException as WebException;
1285
                if (exc == null)
1286
                    throw ex.InnerException;
1287
                if (HandleUploadWebException(action, exc)) 
1288
                    return;
1289
                throw;
1290
            }
1291
            catch (WebException ex)
1292
            {
1293
                if (HandleUploadWebException(action, ex))
1294
                    return;
1295
                throw;
1296
            }
1297
            catch (Exception ex)
1298
            {
1299
                Log.Error("Unexpected error while uploading file", ex);
1300
                throw;
1301
            }
1302

    
1303
        }
1304

    
1305
        //Returns true if an action concerns a file that was deleted
1306
        private bool IsDeletedFile(CloudAction action)
1307
        {
1308
            //Doesn't work for actions targeting shared files
1309
            if (action.IsShared)
1310
                return false;
1311
            var key = GetFileKey(action.CloudFile);
1312
            DateTime entryDate;
1313
            if (_deletedFiles.TryGetValue(key, out entryDate))
1314
            {
1315
                //If the delete entry was created after this action, abort the action
1316
                if (entryDate > action.Created)
1317
                    return true;
1318
                //Otherwise, remove the stale entry 
1319
                _deletedFiles.TryRemove(key, out entryDate);
1320
            }
1321
            return false;
1322
        }
1323

    
1324
        private bool HandleUploadWebException(CloudAction action, WebException exc)
1325
        {
1326
            var response = exc.Response as HttpWebResponse;
1327
            if (response == null)
1328
                throw exc;
1329
            if (response.StatusCode == HttpStatusCode.Unauthorized)
1330
            {
1331
                Log.Error("Not allowed to upload file", exc);
1332
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1333
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1334
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
1335
                return true;
1336
            }
1337
            return false;
1338
        }
1339

    
1340
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1341
        {
1342
            if (accountInfo == null)
1343
                throw new ArgumentNullException("accountInfo");
1344
            if (cloudFile==null)
1345
                throw new ArgumentNullException("cloudFile");
1346
            if (fileInfo == null)
1347
                throw new ArgumentNullException("fileInfo");
1348
            if (String.IsNullOrWhiteSpace(url))
1349
                throw new ArgumentNullException(url);
1350
            if (treeHash==null)
1351
                throw new ArgumentNullException("treeHash");
1352
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1353
                throw new ArgumentException("Invalid container","cloudFile");
1354
            Contract.EndContractBlock();
1355

    
1356
            var fullFileName = fileInfo.GetProperCapitalization();
1357

    
1358
            var account = cloudFile.Account ?? accountInfo.UserName;
1359
            var container = cloudFile.Container ;
1360

    
1361
            var client = new CloudFilesClient(accountInfo);
1362
            //Send the hashmap to the server            
1363
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
1364
            //If the server returns no missing hashes, we are done
1365
            while (missingHashes.Count > 0)
1366
            {
1367

    
1368
                var buffer = new byte[accountInfo.BlockSize];
1369
                foreach (var missingHash in missingHashes)
1370
                {
1371
                    //Find the proper block
1372
                    var blockIndex = treeHash.HashDictionary[missingHash];
1373
                    var offset = blockIndex*accountInfo.BlockSize;
1374

    
1375
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1376

    
1377
                    try
1378
                    {
1379
                        //And upload the block                
1380
                        await client.PostBlock(account, container, buffer, 0, read);
1381
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1382
                    }
1383
                    catch (Exception exc)
1384
                    {
1385
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1386
                    }
1387

    
1388
                }
1389

    
1390
                //Repeat until there are no more missing hashes                
1391
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
1392
            }
1393
        }
1394

    
1395

    
1396
        public void AddAccount(AccountInfo accountInfo)
1397
        {            
1398
            if (!_accounts.Contains(accountInfo))
1399
                _accounts.Add(accountInfo);
1400
        }
1401
    }
1402

    
1403
   
1404

    
1405

    
1406
}