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