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