Removed old code that used MD5 for small files
[pithos-ms-client] / trunk / Pithos.Core / Agents / NetworkAgent.cs
1 #region
2 /* -----------------------------------------------------------------------
3  * <copyright file="NetworkAgent.cs" company="GRNet">
4  * 
5  * Copyright 2011-2012 GRNET S.A. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or
8  * without modification, are permitted provided that the following
9  * conditions are met:
10  *
11  *   1. Redistributions of source code must retain the above
12  *      copyright notice, this list of conditions and the following
13  *      disclaimer.
14  *
15  *   2. Redistributions in binary form must reproduce the above
16  *      copyright notice, this list of conditions and the following
17  *      disclaimer in the documentation and/or other materials
18  *      provided with the distribution.
19  *
20  *
21  * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  * The views and conclusions contained in the software and
35  * documentation are those of the authors and should not be
36  * interpreted as representing official policies, either expressed
37  * or implied, of GRNET S.A.
38  * </copyright>
39  * -----------------------------------------------------------------------
40  */
41 #endregion
42
43 //TODO: Now there is a UUID tag. This can be used for renames/moves
44
45
46 using System;
47 using System.Collections.Concurrent;
48 using System.Collections.Generic;
49 using System.ComponentModel.Composition;
50 using System.Diagnostics;
51 using System.Diagnostics.Contracts;
52 using System.IO;
53 using System.Linq;
54 using System.Net;
55 using System.Threading;
56 using System.Threading.Tasks;
57 using System.Threading.Tasks.Dataflow;
58 using Castle.ActiveRecord;
59 using Pithos.Interfaces;
60 using Pithos.Network;
61 using log4net;
62
63 namespace Pithos.Core.Agents
64 {
65     //TODO: Ensure all network operations use exact casing. Pithos is case sensitive
66     [Export]
67     public class NetworkAgent
68     {
69         private Agent<CloudAction> _agent;
70
71         [System.ComponentModel.Composition.Import]
72         private DeleteAgent _deleteAgent=new DeleteAgent();
73
74         [System.ComponentModel.Composition.Import]
75         public IStatusKeeper StatusKeeper { get; set; }
76         
77         public IStatusNotification StatusNotification { get; set; }
78
79         private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
80
81         private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
82
83         [System.ComponentModel.Composition.Import]
84         public IPithosSettings Settings { get; set; }
85
86         //The Proceed signals the poll agent that it can proceed with polling. 
87         //Essentially it stops the poll agent to give priority to the network agent
88         //Initially the event is signalled because we don't need to pause
89         private readonly AsyncManualResetEvent _proceedEvent = new AsyncManualResetEvent(true);
90
91         public AsyncManualResetEvent ProceedEvent
92         {
93             get { return _proceedEvent; }
94         }
95
96
97         public void Start()
98         {
99             _agent = Agent<CloudAction>.Start(inbox =>
100             {
101                 Action loop = null;
102                 loop = () =>
103                 {
104                     _deleteAgent.ProceedEvent.Wait();
105                     var message = inbox.Receive();
106                     var process=message.Then(Process,inbox.CancellationToken);
107                     inbox.LoopAsync(process, loop);
108                 };
109                 loop();
110             });
111
112         }
113
114         private async Task Process(CloudAction action)
115         {
116             if (action == null)
117                 throw new ArgumentNullException("action");
118             if (action.AccountInfo==null)
119                 throw new ArgumentException("The action.AccountInfo is empty","action");
120             Contract.EndContractBlock();
121
122
123
124
125             using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
126             {                
127                 Log.InfoFormat("[ACTION] Start Processing {0}", action);
128
129                 var cloudFile = action.CloudFile;
130                 var downloadPath = action.GetDownloadPath();
131
132                 try
133                 {
134                     _proceedEvent.Reset();
135                     UpdateStatus(PithosStatus.Syncing);
136                     var accountInfo = action.AccountInfo;
137
138                     if (action.Action == CloudActionType.DeleteCloud)
139                     {                        
140                         //Redirect deletes to the delete agent 
141                         _deleteAgent.Post((CloudDeleteAction)action);
142                     }
143                     if (_deleteAgent.IsDeletedFile(action))
144                     {
145                         //Clear the status of already deleted files to avoid reprocessing
146                         if (action.LocalFile != null)
147                             this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
148                     }
149                     else
150                     {
151                         switch (action.Action)
152                         {
153                             case CloudActionType.UploadUnconditional:
154                                 //Abort if the file was deleted before we reached this point
155                                 await UploadCloudFile(action);
156                                 break;
157                             case CloudActionType.DownloadUnconditional:
158                                 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
159                                 break;
160                             case CloudActionType.RenameCloud:
161                                 var moveAction = (CloudMoveAction)action;
162                                 RenameCloudFile(accountInfo, moveAction);
163                                 break;
164                             case CloudActionType.MustSynch:
165                                 if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
166                                 {
167                                     await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
168                                 }
169                                 else
170                                 {
171                                     await SyncFiles(accountInfo, action);
172                                 }
173                                 break;
174                         }
175                     }
176                     Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
177                                            action.CloudFile.Name);
178                 }
179                 catch (WebException exc)
180                 {
181                     Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
182                 }
183                 catch (OperationCanceledException)
184                 {
185                     throw;
186                 }
187                 catch (DirectoryNotFoundException)
188                 {
189                     Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
190                         action.Action, action.LocalFile, action.CloudFile);
191                     //Post a delete action for the missing file
192                     Post(new CloudDeleteAction(action));
193                 }
194                 catch (FileNotFoundException)
195                 {
196                     Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
197                         action.Action, action.LocalFile, action.CloudFile);
198                     //Post a delete action for the missing file
199                     Post(new CloudDeleteAction(action));
200                 }
201                 catch (Exception exc)
202                 {
203                     Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
204                                      action.Action, action.LocalFile, action.CloudFile, exc);
205
206                     _agent.Post(action);
207                 }
208                 finally
209                 {
210                     if (_agent.IsEmpty)
211                         _proceedEvent.Set();
212                     UpdateStatus(PithosStatus.InSynch);                                        
213                 }
214             }
215         }
216
217         private void UpdateStatus(PithosStatus status)
218         {
219             StatusKeeper.SetPithosStatus(status);
220             StatusNotification.Notify(new Notification());
221         }
222
223         
224         private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
225         {
226             if (accountInfo == null)
227                 throw new ArgumentNullException("accountInfo");
228             if (action==null)
229                 throw new ArgumentNullException("action");
230             if (action.LocalFile==null)
231                 throw new ArgumentException("The action's local file is not specified","action");
232             if (!Path.IsPathRooted(action.LocalFile.FullName))
233                 throw new ArgumentException("The action's local file path must be absolute","action");
234             if (action.CloudFile== null)
235                 throw new ArgumentException("The action's cloud file is not specified", "action");
236             Contract.EndContractBlock();
237
238             var localFile = action.LocalFile;
239             var cloudFile = action.CloudFile;
240             var downloadPath=action.LocalFile.GetProperCapitalization();
241
242             var cloudHash = cloudFile.Hash.ToLower();
243             var previousCloudHash = cloudFile.PreviousHash.ToLower();
244             var localHash = action.LocalHash.Value.ToLower();
245             var topHash = action.TopHash.Value.ToLower();
246
247             //At this point we know that an object has changed on the server and that a local
248             //file already exists. We need to decide whether the file has only changed on 
249             //the server or there is a conflicting change on the client.
250             //
251             
252             //Not enough to compare only the local hashes (MD5), also have to compare the tophashes            
253             //If any of the hashes match, we are done
254             if ((cloudHash == localHash || cloudHash == topHash))
255             {
256                 Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
257                 return;
258             }
259
260             //The hashes DON'T match. We need to sync
261
262             // If the previous tophash matches the local tophash, the file was only changed on the server. 
263             if (localHash == previousCloudHash)
264             {
265                 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
266             }
267             else
268             {
269                 //If the previous and local hash don't match, there was a local conflict
270                 //that was not uploaded to the server. We have a conflict
271                 ReportConflict(downloadPath);
272             }
273         }
274
275         private void ReportConflict(string downloadPath)
276         {
277             if (String.IsNullOrWhiteSpace(downloadPath))
278                 throw new ArgumentNullException("downloadPath");
279             Contract.EndContractBlock();
280
281             StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
282             UpdateStatus(PithosStatus.HasConflicts);
283             var message = String.Format("Conflict detected for file {0}", downloadPath);
284             Log.Warn(message);
285             StatusNotification.NotifyChange(message, TraceLevel.Warning);
286         }
287
288         public void Post(CloudAction cloudAction)
289         {
290             if (cloudAction == null)
291                 throw new ArgumentNullException("cloudAction");
292             if (cloudAction.AccountInfo==null)
293                 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
294             Contract.EndContractBlock();
295
296             _deleteAgent.ProceedEvent.Wait();
297
298             //If the action targets a local file, add a treehash calculation
299             if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
300             {
301                 var accountInfo = cloudAction.AccountInfo;
302                 var localFile = (FileInfo) cloudAction.LocalFile;
303                 if (localFile.Length > accountInfo.BlockSize)
304                     cloudAction.TopHash =
305                         new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
306                                                                                 accountInfo.BlockSize,
307                                                                                 accountInfo.BlockHash, Settings.HashingParallelism).Result
308                                                     .TopHash.ToHashString());
309                 else
310                 {
311                     cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
312                 }
313             }
314             else
315             {
316                 //The hash for a directory is the empty string
317                 cloudAction.TopHash = new Lazy<string>(() => String.Empty);
318             }
319             
320             if (cloudAction is CloudDeleteAction)
321                 _deleteAgent.Post((CloudDeleteAction)cloudAction);
322             else
323                 _agent.Post(cloudAction);
324         }
325        
326
327         public IEnumerable<CloudAction> GetEnumerable()
328         {
329             return _agent.GetEnumerable();
330         }
331
332         public Task GetDeleteAwaiter()
333         {
334             return _deleteAgent.ProceedEvent.WaitAsync();
335         }
336         public CancellationToken CancellationToken
337         {
338             get { return _agent.CancellationToken; }
339         }
340
341         private static FileAgent GetFileAgent(AccountInfo accountInfo)
342         {
343             return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
344         }
345
346
347
348         private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
349         {
350             if (accountInfo==null)
351                 throw new ArgumentNullException("accountInfo");
352             if (action==null)
353                 throw new ArgumentNullException("action");
354             if (action.CloudFile==null)
355                 throw new ArgumentException("CloudFile","action");
356             if (action.LocalFile==null)
357                 throw new ArgumentException("LocalFile","action");
358             if (action.OldLocalFile==null)
359                 throw new ArgumentException("OldLocalFile","action");
360             if (action.OldCloudFile==null)
361                 throw new ArgumentException("OldCloudFile","action");
362             Contract.EndContractBlock();
363             
364             
365             var newFilePath = action.LocalFile.FullName;
366             
367             //How do we handle concurrent renames and deletes/uploads/downloads?
368             //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
369             //  This should never happen as the network agent executes only one action at a time
370             //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
371             //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
372             //  same name will fail.
373             //  This should never happen as the network agent executes only one action at a time.
374             //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
375             //  to remove the rename from the queue.
376             //  We can probably ignore this case. It will result in an error which should be ignored            
377
378             
379             //The local file is already renamed
380             StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
381
382
383             var account = action.CloudFile.Account ?? accountInfo.UserName;
384             var container = action.CloudFile.Container;
385             
386             var client = new CloudFilesClient(accountInfo);
387             //TODO: What code is returned when the source file doesn't exist?
388             client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
389
390             StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
391             StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
392             NativeMethods.RaiseChangeNotification(newFilePath);
393         }
394
395         //Download a file.
396         private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
397         {
398             if (accountInfo == null)
399                 throw new ArgumentNullException("accountInfo");
400             if (cloudFile == null)
401                 throw new ArgumentNullException("cloudFile");
402             if (String.IsNullOrWhiteSpace(cloudFile.Account))
403                 throw new ArgumentNullException("cloudFile");
404             if (String.IsNullOrWhiteSpace(cloudFile.Container))
405                 throw new ArgumentNullException("cloudFile");
406             if (String.IsNullOrWhiteSpace(filePath))
407                 throw new ArgumentNullException("filePath");
408             if (!Path.IsPathRooted(filePath))
409                 throw new ArgumentException("The filePath must be rooted", "filePath");
410             Contract.EndContractBlock();
411             
412
413             var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
414             var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
415
416             var url = relativeUrl.ToString();
417             if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
418                 return;
419
420
421             //Are we already downloading or uploading the file? 
422             using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
423             {
424                 if (gate.Failed)
425                     return;
426                 
427                 var client = new CloudFilesClient(accountInfo);
428                 var account = cloudFile.Account;
429                 var container = cloudFile.Container;
430
431                 if (cloudFile.Content_Type == @"application/directory")
432                 {
433                     if (!Directory.Exists(localPath))
434                         Directory.CreateDirectory(localPath);
435                 }
436                 else
437                 {                    
438                     //Retrieve the hashmap from the server
439                     var serverHash = await client.GetHashMap(account, container, url);
440                     //If it's a small file
441                     if (serverHash.Hashes.Count == 1)
442                         //Download it in one go
443                         await
444                             DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
445                         //Otherwise download it block by block
446                     else
447                         await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
448
449                     if (cloudFile.AllowedTo == "read")
450                     {
451                         var attributes = File.GetAttributes(localPath);
452                         File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
453                     }
454                 }
455
456                 //Now we can store the object's metadata without worrying about ghost status entries
457                 StatusKeeper.StoreInfo(localPath, cloudFile);
458                 
459             }
460         }
461
462         //Download a small file with a single GET operation
463         private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
464         {
465             if (client == null)
466                 throw new ArgumentNullException("client");
467             if (cloudFile==null)
468                 throw new ArgumentNullException("cloudFile");
469             if (relativeUrl == null)
470                 throw new ArgumentNullException("relativeUrl");
471             if (String.IsNullOrWhiteSpace(filePath))
472                 throw new ArgumentNullException("filePath");
473             if (!Path.IsPathRooted(filePath))
474                 throw new ArgumentException("The localPath must be rooted", "filePath");
475             Contract.EndContractBlock();
476
477             var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
478             //If the file already exists
479             if (File.Exists(localPath))
480             {
481                 //First check with MD5 as this is a small file
482                 var localMD5 = Signature.CalculateMD5(localPath);
483                 var cloudHash=serverHash.TopHash.ToHashString();
484                 if (localMD5==cloudHash)
485                     return;
486                 //Then check with a treehash
487                 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
488                 var localHash = localTreeHash.TopHash.ToHashString();
489                 if (localHash==cloudHash)
490                     return;
491             }
492             StatusNotification.Notify(new CloudNotification { Data = cloudFile });
493
494             var fileAgent = GetFileAgent(accountInfo);
495             //Calculate the relative file path for the new file
496             var relativePath = relativeUrl.RelativeUriToFilePath();
497             //The file will be stored in a temporary location while downloading with an extension .download
498             var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
499             //Make sure the target folder exists. DownloadFileTask will not create the folder
500             var tempFolder = Path.GetDirectoryName(tempPath);
501             if (!Directory.Exists(tempFolder))
502                 Directory.CreateDirectory(tempFolder);
503
504             //Download the object to the temporary location
505             await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
506
507             //Create the local folder if it doesn't exist (necessary for shared objects)
508             var localFolder = Path.GetDirectoryName(localPath);
509             if (!Directory.Exists(localFolder))
510                 Directory.CreateDirectory(localFolder);            
511             //And move it to its actual location once downloading is finished
512             if (File.Exists(localPath))
513                 File.Replace(tempPath,localPath,null,true);
514             else
515                 File.Move(tempPath,localPath);
516             //Notify listeners that a local file has changed
517             StatusNotification.NotifyChangedFile(localPath);
518
519                        
520         }
521
522         //Download a file asynchronously using blocks
523         public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
524         {
525             if (client == null)
526                 throw new ArgumentNullException("client");
527             if (cloudFile == null)
528                 throw new ArgumentNullException("cloudFile");
529             if (relativeUrl == null)
530                 throw new ArgumentNullException("relativeUrl");
531             if (String.IsNullOrWhiteSpace(filePath))
532                 throw new ArgumentNullException("filePath");
533             if (!Path.IsPathRooted(filePath))
534                 throw new ArgumentException("The filePath must be rooted", "filePath");
535             if (serverHash == null)
536                 throw new ArgumentNullException("serverHash");
537             Contract.EndContractBlock();
538             
539            var fileAgent = GetFileAgent(accountInfo);
540             var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
541             
542             //Calculate the relative file path for the new file
543             var relativePath = relativeUrl.RelativeUriToFilePath();
544             var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
545
546             
547                         
548             //Calculate the file's treehash
549             var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
550                 
551             //And compare it with the server's hash
552             var upHashes = serverHash.GetHashesAsStrings();
553             var localHashes = treeHash.HashDictionary;
554             for (int i = 0; i < upHashes.Length; i++)
555             {
556                 //For every non-matching hash
557                 var upHash = upHashes[i];
558                 if (!localHashes.ContainsKey(upHash))
559                 {
560                     StatusNotification.Notify(new CloudNotification { Data = cloudFile });
561
562                     if (blockUpdater.UseOrphan(i, upHash))
563                     {
564                         Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
565                         continue;
566                     }
567                     Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
568                     var start = i*serverHash.BlockSize;
569                     //To download the last block just pass a null for the end of the range
570                     long? end = null;
571                     if (i < upHashes.Length - 1 )
572                         end= ((i + 1)*serverHash.BlockSize) ;
573                             
574                     //Download the missing block
575                     var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
576
577                     //and store it
578                     blockUpdater.StoreBlock(i, block);
579
580
581                     Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
582                 }
583             }
584
585             //Want to avoid notifications if no changes were made
586             var hasChanges = blockUpdater.HasBlocks;
587             blockUpdater.Commit();
588             
589             if (hasChanges)
590                 //Notify listeners that a local file has changed
591                 StatusNotification.NotifyChangedFile(localPath);
592
593             Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
594         }
595
596
597         private async Task UploadCloudFile(CloudAction action)
598         {
599             if (action == null)
600                 throw new ArgumentNullException("action");           
601             Contract.EndContractBlock();
602
603             try
604             {                
605                 var accountInfo = action.AccountInfo;
606
607                 var fileInfo = action.LocalFile;
608
609                 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
610                     return;
611                 
612                 var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
613                 if (relativePath.StartsWith(FolderConstants.OthersFolder))
614                 {
615                     var parts = relativePath.Split('\\');
616                     var accountName = parts[1];
617                     var oldName = accountInfo.UserName;
618                     var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
619                     var nameIndex = absoluteUri.IndexOf(oldName);
620                     var root = absoluteUri.Substring(0, nameIndex);
621
622                     accountInfo = new AccountInfo
623                     {
624                         UserName = accountName,
625                         AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
626                         StorageUri = new Uri(root + accountName),
627                         BlockHash = accountInfo.BlockHash,
628                         BlockSize = accountInfo.BlockSize,
629                         Token = accountInfo.Token
630                     };
631                 }
632
633
634                 var fullFileName = fileInfo.GetProperCapitalization();
635                 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
636                 {
637                     //Abort if the file is already being uploaded or downloaded
638                     if (gate.Failed)
639                         return;
640
641                     var cloudFile = action.CloudFile;
642                     var account = cloudFile.Account ?? accountInfo.UserName;
643
644                     var client = new CloudFilesClient(accountInfo);                    
645                     //Even if GetObjectInfo times out, we can proceed with the upload            
646                     var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
647
648                     //If this is a read-only file, do not upload changes
649                     if (info.AllowedTo == "read")
650                         return;
651                     
652                     //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
653                     if (fileInfo is DirectoryInfo)
654                     {
655                         //If the directory doesn't exist the Hash property will be empty
656                         if (String.IsNullOrWhiteSpace(info.Hash))
657                             //Go on and create the directory
658                             await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
659                     }
660                     else
661                     {
662
663                         var cloudHash = info.Hash.ToLower();
664
665                         var hash = action.LocalHash.Value;
666                         var topHash = action.TopHash.Value;
667
668                         //If the file hashes match, abort the upload
669                         if (hash == cloudHash || topHash == cloudHash)
670                         {
671                             //but store any metadata changes 
672                             StatusKeeper.StoreInfo(fullFileName, info);
673                             Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
674                             return;
675                         }
676
677
678                         //Mark the file as modified while we upload it
679                         StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
680                         //And then upload it
681
682                         //Upload even small files using the Hashmap. The server may already contain
683                         //the relevant block
684
685                         //First, calculate the tree hash
686                         var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
687                                                                               accountInfo.BlockHash, 2);
688
689                         await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
690                     }
691                     //If everything succeeds, change the file and overlay status to normal
692                     StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
693                 }
694                 //Notify the Shell to update the overlays
695                 NativeMethods.RaiseChangeNotification(fullFileName);
696                 StatusNotification.NotifyChangedFile(fullFileName);
697             }
698             catch (AggregateException ex)
699             {
700                 var exc = ex.InnerException as WebException;
701                 if (exc == null)
702                     throw ex.InnerException;
703                 if (HandleUploadWebException(action, exc)) 
704                     return;
705                 throw;
706             }
707             catch (WebException ex)
708             {
709                 if (HandleUploadWebException(action, ex))
710                     return;
711                 throw;
712             }
713             catch (Exception ex)
714             {
715                 Log.Error("Unexpected error while uploading file", ex);
716                 throw;
717             }
718
719         }
720
721
722
723         private bool HandleUploadWebException(CloudAction action, WebException exc)
724         {
725             var response = exc.Response as HttpWebResponse;
726             if (response == null)
727                 throw exc;
728             if (response.StatusCode == HttpStatusCode.Unauthorized)
729             {
730                 Log.Error("Not allowed to upload file", exc);
731                 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
732                 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
733                 StatusNotification.NotifyChange(message, TraceLevel.Warning);
734                 return true;
735             }
736             return false;
737         }
738
739         public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
740         {
741             if (accountInfo == null)
742                 throw new ArgumentNullException("accountInfo");
743             if (cloudFile==null)
744                 throw new ArgumentNullException("cloudFile");
745             if (fileInfo == null)
746                 throw new ArgumentNullException("fileInfo");
747             if (String.IsNullOrWhiteSpace(url))
748                 throw new ArgumentNullException(url);
749             if (treeHash==null)
750                 throw new ArgumentNullException("treeHash");
751             if (String.IsNullOrWhiteSpace(cloudFile.Container) )
752                 throw new ArgumentException("Invalid container","cloudFile");
753             Contract.EndContractBlock();
754
755             var fullFileName = fileInfo.GetProperCapitalization();
756
757             var account = cloudFile.Account ?? accountInfo.UserName;
758             var container = cloudFile.Container ;
759
760             var client = new CloudFilesClient(accountInfo);
761             //Send the hashmap to the server            
762             var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
763             //If the server returns no missing hashes, we are done
764             while (missingHashes.Count > 0)
765             {
766
767                 var buffer = new byte[accountInfo.BlockSize];
768                 foreach (var missingHash in missingHashes)
769                 {
770                     //Find the proper block
771                     var blockIndex = treeHash.HashDictionary[missingHash];
772                     var offset = blockIndex*accountInfo.BlockSize;
773
774                     var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
775
776                     try
777                     {
778                         //And upload the block                
779                         await client.PostBlock(account, container, buffer, 0, read);
780                         Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
781                     }
782                     catch (Exception exc)
783                     {
784                         Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
785                     }
786
787                 }
788
789                 //Repeat until there are no more missing hashes                
790                 missingHashes = await client.PutHashMap(account, container, url, treeHash);
791             }
792         }
793
794
795         public void AddAccount(AccountInfo accountInfo)
796         {            
797             if (!_accounts.Contains(accountInfo))
798                 _accounts.Add(accountInfo);
799         }
800     }
801
802    
803
804
805 }