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