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