Extracted cloud delete functionality to a separate DeleteAgent
[pithos-ms-client] / trunk / Pithos.Core / Agents / NetworkAgent.cs
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         [System.ComponentModel.Composition.Import]
64         private DeleteAgent _deleteAgent=new DeleteAgent();
65
66         [System.ComponentModel.Composition.Import]
67         public IStatusKeeper StatusKeeper { get; set; }
68         
69         public IStatusNotification StatusNotification { get; set; }
70
71         private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
72
73         private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
74
75         [System.ComponentModel.Composition.Import]
76         public IPithosSettings Settings { get; set; }
77
78         private bool _firstPoll = true;
79         
80         //The Sync Event signals a manual synchronisation
81         private readonly AsyncManualResetEvent _syncEvent=new AsyncManualResetEvent();
82
83         private ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();
84
85         public void Start()
86         {
87             _firstPoll = true;
88             _agent = Agent<CloudAction>.Start(inbox =>
89             {
90                 Action loop = null;
91                 loop = () =>
92                 {
93                     _deleteAgent.PauseEvent.Wait();
94                     var message = inbox.Receive();
95                     var process=message.Then(Process,inbox.CancellationToken);
96                     inbox.LoopAsync(process, loop);
97                 };
98                 loop();
99             });
100
101         }
102
103         private async Task Process(CloudAction action)
104         {
105             if (action == null)
106                 throw new ArgumentNullException("action");
107             if (action.AccountInfo==null)
108                 throw new ArgumentException("The action.AccountInfo is empty","action");
109             Contract.EndContractBlock();
110
111             UpdateStatus(PithosStatus.Syncing);
112             var accountInfo = action.AccountInfo;
113
114             using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
115             {                
116                 Log.InfoFormat("[ACTION] Start Processing {0}", action);
117
118                 var cloudFile = action.CloudFile;
119                 var downloadPath = action.GetDownloadPath();
120
121                 try
122                 {                    
123                     if (action.Action == CloudActionType.DeleteCloud)
124                     {                        
125                         //Redirect deletes to the delete agent 
126                         _deleteAgent.Post((CloudDeleteAction)action);
127                     }
128                     if (_deleteAgent.IsDeletedFile(action))
129                     {
130                         //Clear the status of already deleted files to avoid reprocessing
131                         if (action.LocalFile != null)
132                             this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
133                     }
134                     else
135                     {
136                         switch (action.Action)
137                         {
138                             case CloudActionType.UploadUnconditional:
139                                 //Abort if the file was deleted before we reached this point
140                                 await UploadCloudFile(action);
141                                 break;
142                             case CloudActionType.DownloadUnconditional:
143                                 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
144                                 break;
145                             case CloudActionType.RenameCloud:
146                                 var moveAction = (CloudMoveAction)action;
147                                 RenameCloudFile(accountInfo, moveAction);
148                                 break;
149                             case CloudActionType.MustSynch:
150                                 if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
151                                 {
152                                     await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
153                                 }
154                                 else
155                                 {
156                                     await SyncFiles(accountInfo, action);
157                                 }
158                                 break;
159                         }
160                     }
161                     Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
162                                            action.CloudFile.Name);
163                 }
164                 catch (WebException exc)
165                 {
166                     Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
167                 }
168                 catch (OperationCanceledException)
169                 {
170                     throw;
171                 }
172                 catch (DirectoryNotFoundException)
173                 {
174                     Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
175                         action.Action, action.LocalFile, action.CloudFile);
176                     //Post a delete action for the missing file
177                     Post(new CloudDeleteAction(action));
178                 }
179                 catch (FileNotFoundException)
180                 {
181                     Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
182                         action.Action, action.LocalFile, action.CloudFile);
183                     //Post a delete action for the missing file
184                     Post(new CloudDeleteAction(action));
185                 }
186                 catch (Exception exc)
187                 {
188                     Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
189                                      action.Action, action.LocalFile, action.CloudFile, exc);
190
191                     _agent.Post(action);
192                 }
193                 finally
194                 {
195                     UpdateStatus(PithosStatus.InSynch);                    
196                 }
197             }
198         }
199
200         private void UpdateStatus(PithosStatus status)
201         {
202             StatusKeeper.SetPithosStatus(status);
203             StatusNotification.Notify(new Notification());
204         }
205
206         
207         private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
208         {
209             if (accountInfo == null)
210                 throw new ArgumentNullException("accountInfo");
211             if (action==null)
212                 throw new ArgumentNullException("action");
213             if (action.LocalFile==null)
214                 throw new ArgumentException("The action's local file is not specified","action");
215             if (!Path.IsPathRooted(action.LocalFile.FullName))
216                 throw new ArgumentException("The action's local file path must be absolute","action");
217             if (action.CloudFile== null)
218                 throw new ArgumentException("The action's cloud file is not specified", "action");
219             Contract.EndContractBlock();
220
221             var localFile = action.LocalFile;
222             var cloudFile = action.CloudFile;
223             var downloadPath=action.LocalFile.GetProperCapitalization();
224
225             var cloudHash = cloudFile.Hash.ToLower();
226             var localHash = action.LocalHash.Value.ToLower();
227             var topHash = action.TopHash.Value.ToLower();
228
229             //Not enough to compare only the local hashes, also have to compare the tophashes
230             
231             //If any of the hashes match, we are done
232             if ((cloudHash == localHash || cloudHash == topHash))
233             {
234                 Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
235                 return;
236             }
237
238             //The hashes DON'T match. We need to sync
239             var lastLocalTime = localFile.LastWriteTime;
240             var lastUpTime = cloudFile.Last_Modified;
241             
242             //If the local file is newer upload it
243             if (lastUpTime <= lastLocalTime)
244             {
245                 //It probably means it was changed while the app was down                        
246                 UploadCloudFile(action);
247             }
248             else
249             {
250                 //It the cloud file has a later date, it was modified by another user or computer.
251                 //We need to check the local file's status                
252                 var status = StatusKeeper.GetFileStatus(downloadPath);
253                 switch (status)
254                 {
255                     case FileStatus.Unchanged:                        
256                         //If the local file's status is Unchanged, we can go on and download the newer cloud file
257                         await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
258                         break;
259                     case FileStatus.Modified:
260                         //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
261                         //We can't ensure that a file modified online since the last time will appear as Modified, unless we 
262                         //index all files before we start listening.                       
263                     case FileStatus.Created:
264                         //If the local file is Created, it means that the local and cloud files aren't related,
265                         // yet they have the same name.
266
267                         //In both cases we must mark the file as in conflict
268                         ReportConflict(downloadPath);
269                         break;
270                     default:
271                         //Other cases should never occur. Mark them as Conflict as well but log a warning
272                         ReportConflict(downloadPath);
273                         Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
274                                        downloadPath, action.CloudFile.Name);
275                         break;
276                 }
277             }
278         }
279
280         private void ReportConflict(string downloadPath)
281         {
282             if (String.IsNullOrWhiteSpace(downloadPath))
283                 throw new ArgumentNullException("downloadPath");
284             Contract.EndContractBlock();
285
286             StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
287             UpdateStatus(PithosStatus.HasConflicts);
288             var message = String.Format("Conflict detected for file {0}", downloadPath);
289             Log.Warn(message);
290             StatusNotification.NotifyChange(message, TraceLevel.Warning);
291         }
292
293         public void Post(CloudAction cloudAction)
294         {
295             if (cloudAction == null)
296                 throw new ArgumentNullException("cloudAction");
297             if (cloudAction.AccountInfo==null)
298                 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
299             Contract.EndContractBlock();
300
301             _deleteAgent.PauseEvent.Wait();
302
303             //If the action targets a local file, add a treehash calculation
304             if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
305             {
306                 var accountInfo = cloudAction.AccountInfo;
307                 var localFile = (FileInfo) cloudAction.LocalFile;
308                 if (localFile.Length > accountInfo.BlockSize)
309                     cloudAction.TopHash =
310                         new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
311                                                                                 accountInfo.BlockSize,
312                                                                                 accountInfo.BlockHash, Settings.HashingParallelism).Result
313                                                     .TopHash.ToHashString());
314                 else
315                 {
316                     cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
317                 }
318             }
319             else
320             {
321                 //The hash for a directory is the empty string
322                 cloudAction.TopHash = new Lazy<string>(() => String.Empty);
323             }
324             
325             if (cloudAction is CloudDeleteAction)
326                 _deleteAgent.Post((CloudDeleteAction)cloudAction);
327             else
328                 _agent.Post(cloudAction);
329         }
330        
331
332         /// <summary>
333         /// Start a manual synchronization
334         /// </summary>
335         public void SynchNow()
336         {       
337             _syncEvent.Set();
338         }
339
340         //Remote files are polled periodically. Any changes are processed
341         public async Task PollRemoteFiles(DateTime? since = null)
342         {
343             UpdateStatus(PithosStatus.Syncing);
344             StatusNotification.Notify(new PollNotification());
345
346             using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
347             {
348                 //If this poll fails, we will retry with the same since value
349                 var nextSince = since;
350                 try
351                 {
352                     //Next time we will check for all changes since the current check minus 1 second
353                     //This is done to ensure there are no discrepancies due to clock differences
354                     var current = DateTime.Now.AddSeconds(-1);
355
356                     var tasks = from accountInfo in _accounts
357                                 select ProcessAccountFiles(accountInfo, since);
358
359                     await TaskEx.WhenAll(tasks.ToList());
360                                         
361                     _firstPoll = false;
362                     //Reschedule the poll with the current timestamp as a "since" value
363                     nextSince = current;
364                 }
365                 catch (Exception ex)
366                 {
367                     Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
368                     //In case of failure retry with the same "since" value
369                 }
370                 
371                 UpdateStatus(PithosStatus.InSynch);
372                 //Wait for the polling interval to pass or the Sync event to be signalled
373                 nextSince = await WaitForScheduledOrManualPoll(nextSince);
374
375                 PollRemoteFiles(nextSince);
376
377             }
378         }
379
380         /// <summary>
381         /// Wait for the polling period to expire or a manual sync request
382         /// </summary>
383         /// <param name="since"></param>
384         /// <returns></returns>
385         private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
386         {
387             var sync=_syncEvent.WaitAsync();
388             var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
389             var signaledTask = await TaskEx.WhenAny(sync, wait);            
390             
391             //If polling is signalled by SynchNow, ignore the since tag
392             if (signaledTask is Task<bool>)
393                 return null;
394             return since;
395         }
396
397         public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
398         {   
399             if (accountInfo==null)
400                 throw new ArgumentNullException("accountInfo");
401             if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
402                 throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
403             Contract.EndContractBlock();
404
405
406             using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
407             {
408                 await _deleteAgent.PauseEvent.WaitAsync();
409
410                 Log.Info("Scheduled");
411                 var client = new CloudFilesClient(accountInfo)
412                                  {
413                                      Proxy = PithosMonitor.ProxyFromSettings(this.Settings)
414                                  };
415
416                 var containers = client.ListContainers(accountInfo.UserName);
417
418
419                 CreateContainerFolders(accountInfo, containers);
420
421                 try
422                 {
423                     await _deleteAgent.PauseEvent.WaitAsync();
424                     //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
425                     //than delete a file that was created while we were executing the poll                    
426                     var pollTime = DateTime.Now;
427                     
428                     //Get the list of server objects changed since the last check
429                     //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
430                     var listObjects = (from container in containers
431                                       select  Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
432                                             client.ListObjects(accountInfo.UserName,container.Name, since),container.Name)).ToList();
433
434                     var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => client.ListSharedObjects(since), "shared");
435                     listObjects.Add(listShared);
436                     var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
437
438                     using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
439                     {
440                         var dict = listTasks.ToDictionary(t => t.AsyncState);
441
442                         //Get all non-trash objects. Remember, the container name is stored in AsyncState
443                         var remoteObjects = from objectList in listTasks
444                                             where (string) objectList.AsyncState != "trash"
445                                             from obj in objectList.Result
446                                             select obj;
447
448                         var trashObjects = dict["trash"].Result;
449                         var sharedObjects = dict["shared"].Result;
450
451                         //Items with the same name, hash may be both in the container and the trash
452                         //Don't delete items that exist in the container
453                         var realTrash = from trash in trashObjects
454                                         where
455                                             !remoteObjects.Any(
456                                                 info => info.Name == trash.Name && info.Hash == trash.Hash)
457                                         select trash;
458                         ProcessTrashedFiles(accountInfo, realTrash);
459
460                         var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
461                                      let name = info.Name
462                                      where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
463                                            !name.StartsWith(FolderConstants.CacheFolder + "/",
464                                                             StringComparison.InvariantCultureIgnoreCase)
465                                      select info).ToList();
466
467                         var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);
468                         
469                         ProcessDeletedFiles(accountInfo, differencer.Deleted, pollTime);
470
471                         //Create a list of actions from the remote files
472                         var allActions = ChangesToActions(accountInfo, differencer.Changed)
473                                         .Union(
474                                         CreatesToActions(accountInfo,differencer.Created));
475                         
476                         //And remove those that are already being processed by the agent
477                         var distinctActions = allActions
478                             .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
479                             .ToList();
480
481                         //Queue all the actions
482                         foreach (var message in distinctActions)
483                         {
484                             Post(message);
485                         }
486
487                         Log.Info("[LISTENER] End Processing");
488                     }
489                 }
490                 catch (Exception ex)
491                 {
492                     Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
493                     return;
494                 }
495
496                 Log.Info("[LISTENER] Finished");
497
498             }
499         }
500
501         AccountsDifferencer _differencer= new AccountsDifferencer();
502
503         /// <summary>
504         /// Deletes local files that are not found in the list of cloud files
505         /// </summary>
506         /// <param name="accountInfo"></param>
507         /// <param name="cloudFiles"></param>
508         /// <param name="pollTime"></param>
509         private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
510         {
511             if (accountInfo == null)
512                 throw new ArgumentNullException("accountInfo");
513             if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
514                 throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
515             if (cloudFiles == null)
516                 throw new ArgumentNullException("cloudFiles");
517             Contract.EndContractBlock();
518
519             //On the first run
520             if (_firstPoll)
521             {
522                 //Only consider files that are not being modified, ie they are in the Unchanged state            
523                 var deleteCandidates = FileState.Queryable.Where(state =>
524                     state.FilePath.StartsWith(accountInfo.AccountPath)
525                     && state.FileStatus == FileStatus.Unchanged).ToList();
526
527
528                 //TODO: filesToDelete must take into account the Others container            
529                 var filesToDelete = (from deleteCandidate in deleteCandidates
530                                          let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
531                                          let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
532                                      where
533                                          !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)
534                                      select localFile).ToList();
535             
536
537
538                 //Set the status of missing files to Conflict
539                 foreach (var item in filesToDelete)
540                 {
541                     //Try to acquire a gate on the file, to take into account files that have been dequeued
542                     //and are being processed
543                     using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
544                     {
545                         if (gate.Failed)
546                             continue;
547                         StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);
548                     }
549                 }
550                 UpdateStatus(PithosStatus.HasConflicts);
551                 StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted",filesToDelete.Count));
552                 StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count), TraceLevel.Info);
553             }
554             else
555             {
556                 var deletedFiles = new List<FileSystemInfo>();
557                 foreach (var objectInfo in cloudFiles)
558                 {
559                     var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
560                     var item = GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);
561                     if (item.Exists)
562                     {
563                         if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
564                         {
565                             item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
566
567                         }
568                         item.Delete();
569                         DateTime lastDate;
570                         _lastSeen.TryRemove(item.FullName, out lastDate);
571                         deletedFiles.Add(item);
572                     }
573                     StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted);                    
574                 }
575                 StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count), TraceLevel.Info);
576             }
577
578         }
579
580         private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
581         {
582             var containerPaths = from container in containers
583                                  let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
584                                  where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
585                                  select containerPath;
586
587             foreach (var path in containerPaths)
588             {
589                 Directory.CreateDirectory(path);
590             }
591         }
592
593         //Creates an appropriate action for each server file
594         private IEnumerable<CloudAction> ChangesToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> changes)
595         {
596             if (changes==null)
597                 throw new ArgumentNullException();
598             Contract.EndContractBlock();
599             var fileAgent = GetFileAgent(accountInfo);
600
601             //In order to avoid multiple iterations over the files, we iterate only once
602             //over the remote files
603             foreach (var objectInfo in changes)
604             {
605                 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
606                 //and remove any matching objects from the list, adding them to the commonObjects list
607                 if (fileAgent.Exists(relativePath))
608                 {
609                     //If a directory object already exists, we don't need to perform any other action                    
610                     var localFile = fileAgent.GetFileSystemInfo(relativePath);
611                     if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
612                         continue;
613                     using (new SessionScope(FlushAction.Never))
614                     {
615                         var state =  StatusKeeper.GetStateByFilePath(localFile.FullName);
616                         _lastSeen[localFile.FullName] = DateTime.Now;
617                         //Common files should be checked on a per-case basis to detect differences, which is newer
618
619                         yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
620                                                      localFile, objectInfo, state, accountInfo.BlockSize,
621                                                      accountInfo.BlockHash);
622                     }
623                 }
624                 else
625                 {
626                     //Remote files should be downloaded
627                     yield return new CloudDownloadAction(accountInfo,objectInfo);
628                 }
629             }            
630         }
631
632         private IEnumerable<CloudAction> CreatesToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> creates)
633         {
634             if (creates==null)
635                 throw new ArgumentNullException();
636             Contract.EndContractBlock();
637             var fileAgent = GetFileAgent(accountInfo);
638
639             //In order to avoid multiple iterations over the files, we iterate only once
640             //over the remote files
641             foreach (var objectInfo in creates)
642             {
643                 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
644                 //and remove any matching objects from the list, adding them to the commonObjects list
645                 if (fileAgent.Exists(relativePath))
646                 {
647                     //If the object already exists, we probably have a conflict
648                     //If a directory object already exists, we don't need to perform any other action                    
649                     var localFile = fileAgent.GetFileSystemInfo(relativePath);
650                     StatusKeeper.SetFileState(localFile.FullName,FileStatus.Conflict,FileOverlayStatus.Conflict);
651                 }
652                 else
653                 {
654                     //Remote files should be downloaded
655                     yield return new CloudDownloadAction(accountInfo,objectInfo);
656                 }
657             }            
658         }
659
660
661         private static FileAgent GetFileAgent(AccountInfo accountInfo)
662         {
663             return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
664         }
665
666         private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
667         {
668             var fileAgent = GetFileAgent(accountInfo);
669             foreach (var trashObject in trashObjects)
670             {
671                 var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
672                 //HACK: Assume only the "pithos" container is used. Must find out what happens when
673                 //deleting a file from a different container
674                 var relativePath = Path.Combine("pithos", barePath);
675                 fileAgent.Delete(relativePath);                                
676             }
677         }
678
679
680         private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
681         {
682             if (accountInfo==null)
683                 throw new ArgumentNullException("accountInfo");
684             if (action==null)
685                 throw new ArgumentNullException("action");
686             if (action.CloudFile==null)
687                 throw new ArgumentException("CloudFile","action");
688             if (action.LocalFile==null)
689                 throw new ArgumentException("LocalFile","action");
690             if (action.OldLocalFile==null)
691                 throw new ArgumentException("OldLocalFile","action");
692             if (action.OldCloudFile==null)
693                 throw new ArgumentException("OldCloudFile","action");
694             Contract.EndContractBlock();
695             
696             
697             var newFilePath = action.LocalFile.FullName;
698             
699             //How do we handle concurrent renames and deletes/uploads/downloads?
700             //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
701             //  This should never happen as the network agent executes only one action at a time
702             //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
703             //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
704             //  same name will fail.
705             //  This should never happen as the network agent executes only one action at a time.
706             //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
707             //  to remove the rename from the queue.
708             //  We can probably ignore this case. It will result in an error which should be ignored            
709
710             
711             //The local file is already renamed
712             StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
713
714
715             var account = action.CloudFile.Account ?? accountInfo.UserName;
716             var container = action.CloudFile.Container;
717             
718             var client = new CloudFilesClient(accountInfo);
719             //TODO: What code is returned when the source file doesn't exist?
720             client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
721
722             StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
723             StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
724             NativeMethods.RaiseChangeNotification(newFilePath);
725         }
726
727         //Download a file.
728         private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
729         {
730             if (accountInfo == null)
731                 throw new ArgumentNullException("accountInfo");
732             if (cloudFile == null)
733                 throw new ArgumentNullException("cloudFile");
734             if (String.IsNullOrWhiteSpace(cloudFile.Account))
735                 throw new ArgumentNullException("cloudFile");
736             if (String.IsNullOrWhiteSpace(cloudFile.Container))
737                 throw new ArgumentNullException("cloudFile");
738             if (String.IsNullOrWhiteSpace(filePath))
739                 throw new ArgumentNullException("filePath");
740             if (!Path.IsPathRooted(filePath))
741                 throw new ArgumentException("The filePath must be rooted", "filePath");
742             Contract.EndContractBlock();
743             
744
745             var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
746             var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
747
748             var url = relativeUrl.ToString();
749             if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
750                 return;
751
752
753             //Are we already downloading or uploading the file? 
754             using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
755             {
756                 if (gate.Failed)
757                     return;
758                 
759                 var client = new CloudFilesClient(accountInfo);
760                 var account = cloudFile.Account;
761                 var container = cloudFile.Container;
762
763                 if (cloudFile.Content_Type == @"application/directory")
764                 {
765                     if (!Directory.Exists(localPath))
766                         Directory.CreateDirectory(localPath);
767                 }
768                 else
769                 {                    
770                     //Retrieve the hashmap from the server
771                     var serverHash = await client.GetHashMap(account, container, url);
772                     //If it's a small file
773                     if (serverHash.Hashes.Count == 1)
774                         //Download it in one go
775                         await
776                             DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
777                         //Otherwise download it block by block
778                     else
779                         await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
780
781                     if (cloudFile.AllowedTo == "read")
782                     {
783                         var attributes = File.GetAttributes(localPath);
784                         File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
785                     }
786                 }
787
788                 //Now we can store the object's metadata without worrying about ghost status entries
789                 StatusKeeper.StoreInfo(localPath, cloudFile);
790                 
791             }
792         }
793
794         //Download a small file with a single GET operation
795         private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
796         {
797             if (client == null)
798                 throw new ArgumentNullException("client");
799             if (cloudFile==null)
800                 throw new ArgumentNullException("cloudFile");
801             if (relativeUrl == null)
802                 throw new ArgumentNullException("relativeUrl");
803             if (String.IsNullOrWhiteSpace(filePath))
804                 throw new ArgumentNullException("filePath");
805             if (!Path.IsPathRooted(filePath))
806                 throw new ArgumentException("The localPath must be rooted", "filePath");
807             Contract.EndContractBlock();
808
809             var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
810             //If the file already exists
811             if (File.Exists(localPath))
812             {
813                 //First check with MD5 as this is a small file
814                 var localMD5 = Signature.CalculateMD5(localPath);
815                 var cloudHash=serverHash.TopHash.ToHashString();
816                 if (localMD5==cloudHash)
817                     return;
818                 //Then check with a treehash
819                 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
820                 var localHash = localTreeHash.TopHash.ToHashString();
821                 if (localHash==cloudHash)
822                     return;
823             }
824             StatusNotification.Notify(new CloudNotification { Data = cloudFile });
825
826             var fileAgent = GetFileAgent(accountInfo);
827             //Calculate the relative file path for the new file
828             var relativePath = relativeUrl.RelativeUriToFilePath();
829             //The file will be stored in a temporary location while downloading with an extension .download
830             var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
831             //Make sure the target folder exists. DownloadFileTask will not create the folder
832             var tempFolder = Path.GetDirectoryName(tempPath);
833             if (!Directory.Exists(tempFolder))
834                 Directory.CreateDirectory(tempFolder);
835
836             //Download the object to the temporary location
837             await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
838
839             //Create the local folder if it doesn't exist (necessary for shared objects)
840             var localFolder = Path.GetDirectoryName(localPath);
841             if (!Directory.Exists(localFolder))
842                 Directory.CreateDirectory(localFolder);            
843             //And move it to its actual location once downloading is finished
844             if (File.Exists(localPath))
845                 File.Replace(tempPath,localPath,null,true);
846             else
847                 File.Move(tempPath,localPath);
848             //Notify listeners that a local file has changed
849             StatusNotification.NotifyChangedFile(localPath);
850
851                        
852         }
853
854         //Download a file asynchronously using blocks
855         public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
856         {
857             if (client == null)
858                 throw new ArgumentNullException("client");
859             if (cloudFile == null)
860                 throw new ArgumentNullException("cloudFile");
861             if (relativeUrl == null)
862                 throw new ArgumentNullException("relativeUrl");
863             if (String.IsNullOrWhiteSpace(filePath))
864                 throw new ArgumentNullException("filePath");
865             if (!Path.IsPathRooted(filePath))
866                 throw new ArgumentException("The filePath must be rooted", "filePath");
867             if (serverHash == null)
868                 throw new ArgumentNullException("serverHash");
869             Contract.EndContractBlock();
870             
871            var fileAgent = GetFileAgent(accountInfo);
872             var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
873             
874             //Calculate the relative file path for the new file
875             var relativePath = relativeUrl.RelativeUriToFilePath();
876             var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
877
878             
879                         
880             //Calculate the file's treehash
881             var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
882                 
883             //And compare it with the server's hash
884             var upHashes = serverHash.GetHashesAsStrings();
885             var localHashes = treeHash.HashDictionary;
886             for (int i = 0; i < upHashes.Length; i++)
887             {
888                 //For every non-matching hash
889                 var upHash = upHashes[i];
890                 if (!localHashes.ContainsKey(upHash))
891                 {
892                     StatusNotification.Notify(new CloudNotification { Data = cloudFile });
893
894                     if (blockUpdater.UseOrphan(i, upHash))
895                     {
896                         Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
897                         continue;
898                     }
899                     Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
900                     var start = i*serverHash.BlockSize;
901                     //To download the last block just pass a null for the end of the range
902                     long? end = null;
903                     if (i < upHashes.Length - 1 )
904                         end= ((i + 1)*serverHash.BlockSize) ;
905                             
906                     //Download the missing block
907                     var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
908
909                     //and store it
910                     blockUpdater.StoreBlock(i, block);
911
912
913                     Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
914                 }
915             }
916
917             //Want to avoid notifications if no changes were made
918             var hasChanges = blockUpdater.HasBlocks;
919             blockUpdater.Commit();
920             
921             if (hasChanges)
922                 //Notify listeners that a local file has changed
923                 StatusNotification.NotifyChangedFile(localPath);
924
925             Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
926         }
927
928
929         private async Task UploadCloudFile(CloudAction action)
930         {
931             if (action == null)
932                 throw new ArgumentNullException("action");           
933             Contract.EndContractBlock();
934
935             try
936             {                
937                 var accountInfo = action.AccountInfo;
938
939                 var fileInfo = action.LocalFile;
940
941                 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
942                     return;
943                 
944                 var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
945                 if (relativePath.StartsWith(FolderConstants.OthersFolder))
946                 {
947                     var parts = relativePath.Split('\\');
948                     var accountName = parts[1];
949                     var oldName = accountInfo.UserName;
950                     var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
951                     var nameIndex = absoluteUri.IndexOf(oldName);
952                     var root = absoluteUri.Substring(0, nameIndex);
953
954                     accountInfo = new AccountInfo
955                     {
956                         UserName = accountName,
957                         AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
958                         StorageUri = new Uri(root + accountName),
959                         BlockHash = accountInfo.BlockHash,
960                         BlockSize = accountInfo.BlockSize,
961                         Token = accountInfo.Token
962                     };
963                 }
964
965
966                 var fullFileName = fileInfo.GetProperCapitalization();
967                 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
968                 {
969                     //Abort if the file is already being uploaded or downloaded
970                     if (gate.Failed)
971                         return;
972
973                     var cloudFile = action.CloudFile;
974                     var account = cloudFile.Account ?? accountInfo.UserName;
975
976                     var client = new CloudFilesClient(accountInfo);                    
977                     //Even if GetObjectInfo times out, we can proceed with the upload            
978                     var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
979
980                     //If this is a read-only file, do not upload changes
981                     if (info.AllowedTo == "read")
982                         return;
983                     
984                     //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
985                     if (fileInfo is DirectoryInfo)
986                     {
987                         //If the directory doesn't exist the Hash property will be empty
988                         if (String.IsNullOrWhiteSpace(info.Hash))
989                             //Go on and create the directory
990                             await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
991                     }
992                     else
993                     {
994
995                         var cloudHash = info.Hash.ToLower();
996
997                         var hash = action.LocalHash.Value;
998                         var topHash = action.TopHash.Value;
999
1000                         //If the file hashes match, abort the upload
1001                         if (hash == cloudHash || topHash == cloudHash)
1002                         {
1003                             //but store any metadata changes 
1004                             StatusKeeper.StoreInfo(fullFileName, info);
1005                             Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1006                             return;
1007                         }
1008
1009
1010                         //Mark the file as modified while we upload it
1011                         StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1012                         //And then upload it
1013
1014                         //Upload even small files using the Hashmap. The server may already contain
1015                         //the relevant block
1016
1017                         //First, calculate the tree hash
1018                         var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1019                                                                               accountInfo.BlockHash, 2);
1020
1021                         await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1022                     }
1023                     //If everything succeeds, change the file and overlay status to normal
1024                     StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1025                 }
1026                 //Notify the Shell to update the overlays
1027                 NativeMethods.RaiseChangeNotification(fullFileName);
1028                 StatusNotification.NotifyChangedFile(fullFileName);
1029             }
1030             catch (AggregateException ex)
1031             {
1032                 var exc = ex.InnerException as WebException;
1033                 if (exc == null)
1034                     throw ex.InnerException;
1035                 if (HandleUploadWebException(action, exc)) 
1036                     return;
1037                 throw;
1038             }
1039             catch (WebException ex)
1040             {
1041                 if (HandleUploadWebException(action, ex))
1042                     return;
1043                 throw;
1044             }
1045             catch (Exception ex)
1046             {
1047                 Log.Error("Unexpected error while uploading file", ex);
1048                 throw;
1049             }
1050
1051         }
1052
1053
1054
1055         private bool HandleUploadWebException(CloudAction action, WebException exc)
1056         {
1057             var response = exc.Response as HttpWebResponse;
1058             if (response == null)
1059                 throw exc;
1060             if (response.StatusCode == HttpStatusCode.Unauthorized)
1061             {
1062                 Log.Error("Not allowed to upload file", exc);
1063                 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1064                 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1065                 StatusNotification.NotifyChange(message, TraceLevel.Warning);
1066                 return true;
1067             }
1068             return false;
1069         }
1070
1071         public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1072         {
1073             if (accountInfo == null)
1074                 throw new ArgumentNullException("accountInfo");
1075             if (cloudFile==null)
1076                 throw new ArgumentNullException("cloudFile");
1077             if (fileInfo == null)
1078                 throw new ArgumentNullException("fileInfo");
1079             if (String.IsNullOrWhiteSpace(url))
1080                 throw new ArgumentNullException(url);
1081             if (treeHash==null)
1082                 throw new ArgumentNullException("treeHash");
1083             if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1084                 throw new ArgumentException("Invalid container","cloudFile");
1085             Contract.EndContractBlock();
1086
1087             var fullFileName = fileInfo.GetProperCapitalization();
1088
1089             var account = cloudFile.Account ?? accountInfo.UserName;
1090             var container = cloudFile.Container ;
1091
1092             var client = new CloudFilesClient(accountInfo);
1093             //Send the hashmap to the server            
1094             var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
1095             //If the server returns no missing hashes, we are done
1096             while (missingHashes.Count > 0)
1097             {
1098
1099                 var buffer = new byte[accountInfo.BlockSize];
1100                 foreach (var missingHash in missingHashes)
1101                 {
1102                     //Find the proper block
1103                     var blockIndex = treeHash.HashDictionary[missingHash];
1104                     var offset = blockIndex*accountInfo.BlockSize;
1105
1106                     var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1107
1108                     try
1109                     {
1110                         //And upload the block                
1111                         await client.PostBlock(account, container, buffer, 0, read);
1112                         Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1113                     }
1114                     catch (Exception exc)
1115                     {
1116                         Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1117                     }
1118
1119                 }
1120
1121                 //Repeat until there are no more missing hashes                
1122                 missingHashes = await client.PutHashMap(account, container, url, treeHash);
1123             }
1124         }
1125
1126
1127         public void AddAccount(AccountInfo accountInfo)
1128         {            
1129             if (!_accounts.Contains(accountInfo))
1130                 _accounts.Add(accountInfo);
1131         }
1132     }
1133
1134    
1135
1136
1137 }