Fixed problems with missing empty directories due to incorrect LocalFileComparer...
[pithos-ms-client] / trunk / Pithos.Core / Agents / PollAgent.cs
1 #region\r
2 /* -----------------------------------------------------------------------\r
3  * <copyright file="PollAgent.cs" company="GRNet">\r
4  * \r
5  * Copyright 2011-2012 GRNET S.A. All rights reserved.\r
6  *\r
7  * Redistribution and use in source and binary forms, with or\r
8  * without modification, are permitted provided that the following\r
9  * conditions are met:\r
10  *\r
11  *   1. Redistributions of source code must retain the above\r
12  *      copyright notice, this list of conditions and the following\r
13  *      disclaimer.\r
14  *\r
15  *   2. Redistributions in binary form must reproduce the above\r
16  *      copyright notice, this list of conditions and the following\r
17  *      disclaimer in the documentation and/or other materials\r
18  *      provided with the distribution.\r
19  *\r
20  *\r
21  * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS\r
22  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r
23  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
24  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR\r
25  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\r
28  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\r
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\r
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\r
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
32  * POSSIBILITY OF SUCH DAMAGE.\r
33  *\r
34  * The views and conclusions contained in the software and\r
35  * documentation are those of the authors and should not be\r
36  * interpreted as representing official policies, either expressed\r
37  * or implied, of GRNET S.A.\r
38  * </copyright>\r
39  * -----------------------------------------------------------------------\r
40  */\r
41 #endregion\r
42 \r
43 using System.Collections.Concurrent;\r
44 using System.ComponentModel.Composition;\r
45 using System.Diagnostics;\r
46 using System.Diagnostics.Contracts;\r
47 using System.IO;\r
48 using System.Reflection;\r
49 using System.Threading;\r
50 using System.Threading.Tasks;\r
51 using Castle.ActiveRecord;\r
52 using Pithos.Interfaces;\r
53 using Pithos.Network;\r
54 using log4net;\r
55 \r
56 namespace Pithos.Core.Agents\r
57 {\r
58     using System;\r
59     using System.Collections.Generic;\r
60     using System.Linq;\r
61 \r
62     /// <summary>\r
63     /// PollAgent periodically polls the server to detect object changes. The agent retrieves a listing of all\r
64     /// objects and compares it with a previously cached version to detect differences. \r
65     /// New files are downloaded, missing files are deleted from the local file system and common files are compared\r
66     /// to determine the appropriate action\r
67     /// </summary>\r
68     [Export]\r
69     public class PollAgent\r
70     {\r
71         private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);\r
72 \r
73         [System.ComponentModel.Composition.Import]\r
74         public IStatusKeeper StatusKeeper { get; set; }\r
75 \r
76         [System.ComponentModel.Composition.Import]\r
77         public IPithosSettings Settings { get; set; }\r
78 \r
79         [System.ComponentModel.Composition.Import]\r
80         public NetworkAgent NetworkAgent { get; set; }\r
81 \r
82         public IStatusNotification StatusNotification { get; set; }\r
83 \r
84         private bool _firstPoll = true;\r
85 \r
86         //The Sync Event signals a manual synchronisation\r
87         private readonly AsyncManualResetEvent _syncEvent = new AsyncManualResetEvent();\r
88 \r
89         private readonly ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();\r
90         private readonly ConcurrentDictionary<string, AccountInfo> _accounts = new ConcurrentDictionary<string,AccountInfo>();\r
91 \r
92 \r
93         /// <summary>\r
94         /// Start a manual synchronization\r
95         /// </summary>\r
96         public void SynchNow()\r
97         {            \r
98             _syncEvent.Set();\r
99         }\r
100 \r
101         /// <summary>\r
102         /// Remote files are polled periodically. Any changes are processed\r
103         /// </summary>\r
104         /// <param name="since"></param>\r
105         /// <returns></returns>\r
106         public async Task PollRemoteFiles(DateTime? since = null)\r
107         {\r
108             if (Log.IsDebugEnabled)\r
109                 Log.DebugFormat("Polling changes after [{0}]",since);\r
110 \r
111             Debug.Assert(Thread.CurrentThread.IsBackground, "Polling Ended up in the main thread!");\r
112             \r
113 \r
114             using (ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))\r
115             {\r
116                 //If this poll fails, we will retry with the same since value\r
117                 var nextSince = since;\r
118                 try\r
119                 {\r
120                     UpdateStatus(PithosStatus.PollSyncing);\r
121 \r
122                     var tasks = from accountInfo in _accounts.Values\r
123                                 select ProcessAccountFiles(accountInfo, since);\r
124 \r
125                     var nextTimes=await TaskEx.WhenAll(tasks.ToList());\r
126 \r
127                     _firstPoll = false;\r
128                     //Reschedule the poll with the current timestamp as a "since" value\r
129 \r
130                     if (nextTimes.Length>0)\r
131                         nextSince = nextTimes.Min();\r
132                     if (Log.IsDebugEnabled)\r
133                         Log.DebugFormat("Next Poll at [{0}]",nextSince);\r
134                 }\r
135                 catch (Exception ex)\r
136                 {\r
137                     Log.ErrorFormat("Error while processing accounts\r\n{0}", ex);\r
138                     //In case of failure retry with the same "since" value\r
139                 }\r
140 \r
141                 UpdateStatus(PithosStatus.PollComplete);\r
142                 //The multiple try blocks are required because we can't have an await call\r
143                 //inside a finally block\r
144                 //TODO: Find a more elegant solution for reschedulling in the event of an exception\r
145                 try\r
146                 {\r
147                     //Wait for the polling interval to pass or the Sync event to be signalled\r
148                     nextSince = await WaitForScheduledOrManualPoll(nextSince);\r
149                 }\r
150                 finally\r
151                 {\r
152                     //Ensure polling is scheduled even in case of error\r
153                     TaskEx.Run(() => PollRemoteFiles(nextSince));                        \r
154                 }\r
155             }\r
156         }\r
157 \r
158         /// <summary>\r
159         /// Wait for the polling period to expire or a manual sync request\r
160         /// </summary>\r
161         /// <param name="since"></param>\r
162         /// <returns></returns>\r
163         private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)\r
164         {\r
165             var sync = _syncEvent.WaitAsync();\r
166             var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), NetworkAgent.CancellationToken);\r
167             var signaledTask = await TaskEx.WhenAny(sync, wait);\r
168 \r
169             //Wait for network processing to finish before polling\r
170             var pauseTask=NetworkAgent.ProceedEvent.WaitAsync();\r
171             await TaskEx.WhenAll(signaledTask, pauseTask);\r
172 \r
173             //If polling is signalled by SynchNow, ignore the since tag\r
174             if (sync.IsCompleted)\r
175             {\r
176                 //TODO: Must convert to AutoReset\r
177                 _syncEvent.Reset();\r
178                 return null;\r
179             }\r
180             return since;\r
181         }\r
182 \r
183         public async Task<DateTime?> ProcessAccountFiles(AccountInfo accountInfo, DateTime? since = null)\r
184         {\r
185             if (accountInfo == null)\r
186                 throw new ArgumentNullException("accountInfo");\r
187             if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))\r
188                 throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");\r
189             Contract.EndContractBlock();\r
190 \r
191 \r
192             using (ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))\r
193             {\r
194 \r
195                 await NetworkAgent.GetDeleteAwaiter();\r
196 \r
197                 Log.Info("Scheduled");\r
198                 var client = new CloudFilesClient(accountInfo);\r
199 \r
200                 //We don't need to check the trash container\r
201                 var containers = client.ListContainers(accountInfo.UserName)\r
202                     .Where(c=>c.Name!="trash")\r
203                     .ToList();\r
204 \r
205 \r
206                 CreateContainerFolders(accountInfo, containers);\r
207 \r
208                 //The nextSince time fallback time is the same as the current.\r
209                 //If polling succeeds, the next Since time will be the smallest of the maximum modification times\r
210                 //of the shared and account objects\r
211                 var nextSince = since;\r
212 \r
213                 try\r
214                 {\r
215                     //Wait for any deletions to finish\r
216                     await NetworkAgent.GetDeleteAwaiter();\r
217                     //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted\r
218                     //than delete a file that was created while we were executing the poll                    \r
219 \r
220                     //Get the list of server objects changed since the last check\r
221                     //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step\r
222                     var listObjects = (from container in containers\r
223                                        select Task<IList<ObjectInfo>>.Factory.StartNew(_ =>\r
224                                              client.ListObjects(accountInfo.UserName, container.Name, since), container.Name)).ToList();\r
225 \r
226                     var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => \r
227                         client.ListSharedObjects(since), "shared");\r
228                     listObjects.Add(listShared);\r
229                     var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());\r
230 \r
231                     using (ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))\r
232                     {\r
233                         var dict = listTasks.ToDictionary(t => t.AsyncState);\r
234 \r
235                         //Get all non-trash objects. Remember, the container name is stored in AsyncState\r
236                         var remoteObjects = (from objectList in listTasks\r
237                                             where (string)objectList.AsyncState != "trash"\r
238                                             from obj in objectList.Result\r
239                                             select obj).ToList();\r
240                         \r
241                         //Get the latest remote object modification date, only if it is after\r
242                         //the original since date\r
243                         nextSince = GetLatestDateAfter(nextSince, remoteObjects);\r
244 \r
245                         var sharedObjects = dict["shared"].Result;\r
246                         nextSince = GetLatestDateBefore(nextSince, sharedObjects);\r
247 \r
248                         //DON'T process trashed files\r
249                         //If some files are deleted and added again to a folder, they will be deleted\r
250                         //even though they are new.\r
251                         //We would have to check file dates and hashes to ensure that a trashed file\r
252                         //can be deleted safely from the local hard drive.\r
253                         /*\r
254                         //Items with the same name, hash may be both in the container and the trash\r
255                         //Don't delete items that exist in the container\r
256                         var realTrash = from trash in trashObjects\r
257                                         where\r
258                                             !remoteObjects.Any(\r
259                                                 info => info.Name == trash.Name && info.Hash == trash.Hash)\r
260                                         select trash;\r
261                         ProcessTrashedFiles(accountInfo, realTrash);\r
262 */\r
263 \r
264                         var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)\r
265                                             let name = info.Name??""\r
266                                             where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&\r
267                                                   !name.StartsWith(FolderConstants.CacheFolder + "/",\r
268                                                                    StringComparison.InvariantCultureIgnoreCase)\r
269                                             select info).ToList();\r
270 \r
271                         var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);\r
272 \r
273                         ProcessDeletedFiles(accountInfo, differencer.Deleted.FilterDirectlyBelow(SelectiveUris));\r
274 \r
275                         // @@@ NEED To add previous state here as well, To compare with previous hash\r
276 \r
277                         \r
278 \r
279                         //Create a list of actions from the remote files\r
280                         var allActions = MovesToActions(accountInfo,differencer.Moved.FilterDirectlyBelow(SelectiveUris))\r
281                                         .Union(\r
282                                         ChangesToActions(accountInfo, differencer.Changed.FilterDirectlyBelow(SelectiveUris)))\r
283                                         .Union(\r
284                                         CreatesToActions(accountInfo, differencer.Created.FilterDirectlyBelow(SelectiveUris)));\r
285 \r
286                         //And remove those that are already being processed by the agent\r
287                         var distinctActions = allActions\r
288                             .Except(NetworkAgent.GetEnumerable(), new LocalFileComparer())\r
289                             .ToList();\r
290 \r
291                         //Queue all the actions\r
292                         foreach (var message in distinctActions)\r
293                         {\r
294                             NetworkAgent.Post(message);\r
295                         }\r
296 \r
297                         Log.Info("[LISTENER] End Processing");\r
298                     }\r
299                 }\r
300                 catch (Exception ex)\r
301                 {\r
302                     Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);\r
303                     return nextSince;\r
304                 }\r
305 \r
306                 Log.Info("[LISTENER] Finished");\r
307                 return nextSince;\r
308             }\r
309         }\r
310 \r
311         /// <summary>\r
312         /// Returns the latest LastModified date from the list of objects, but only if it is before\r
313         /// than the threshold value\r
314         /// </summary>\r
315         /// <param name="threshold"></param>\r
316         /// <param name="cloudObjects"></param>\r
317         /// <returns></returns>\r
318         private static DateTime? GetLatestDateBefore(DateTime? threshold, IList<ObjectInfo> cloudObjects)\r
319         {\r
320             DateTime? maxDate = null;\r
321             if (cloudObjects!=null &&  cloudObjects.Count > 0)\r
322                 maxDate = cloudObjects.Max(obj => obj.Last_Modified);\r
323             if (maxDate == null || maxDate == DateTime.MinValue)\r
324                 return threshold;\r
325             if (threshold == null || threshold == DateTime.MinValue || threshold > maxDate)\r
326                 return maxDate;\r
327             return threshold;\r
328         }\r
329 \r
330         /// <summary>\r
331         /// Returns the latest LastModified date from the list of objects, but only if it is after\r
332         /// the threshold value\r
333         /// </summary>\r
334         /// <param name="threshold"></param>\r
335         /// <param name="cloudObjects"></param>\r
336         /// <returns></returns>\r
337         private static DateTime? GetLatestDateAfter(DateTime? threshold, IList<ObjectInfo> cloudObjects)\r
338         {\r
339             DateTime? maxDate = null;\r
340             if (cloudObjects!=null &&  cloudObjects.Count > 0)\r
341                 maxDate = cloudObjects.Max(obj => obj.Last_Modified);\r
342             if (maxDate == null || maxDate == DateTime.MinValue)\r
343                 return threshold;\r
344             if (threshold == null || threshold == DateTime.MinValue || threshold < maxDate)\r
345                 return maxDate;\r
346             return threshold;\r
347         }\r
348 \r
349         readonly AccountsDifferencer _differencer = new AccountsDifferencer();\r
350         private List<Uri> _selectiveUris=new List<Uri>();\r
351 \r
352         /// <summary>\r
353         /// Deletes local files that are not found in the list of cloud files\r
354         /// </summary>\r
355         /// <param name="accountInfo"></param>\r
356         /// <param name="cloudFiles"></param>\r
357         private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles)\r
358         {\r
359             if (accountInfo == null)\r
360                 throw new ArgumentNullException("accountInfo");\r
361             if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))\r
362                 throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");\r
363             if (cloudFiles == null)\r
364                 throw new ArgumentNullException("cloudFiles");\r
365             Contract.EndContractBlock();\r
366 \r
367             //On the first run\r
368             if (_firstPoll)\r
369             {\r
370                 //Only consider files that are not being modified, ie they are in the Unchanged state            \r
371                 var deleteCandidates = FileState.Queryable.Where(state =>\r
372                     state.FilePath.StartsWith(accountInfo.AccountPath)\r
373                     && state.FileStatus == FileStatus.Unchanged).ToList();\r
374 \r
375 \r
376                 //TODO: filesToDelete must take into account the Others container            \r
377                 var filesToDelete = (from deleteCandidate in deleteCandidates\r
378                                      let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)\r
379                                      let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)\r
380                                      where\r
381                                          !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)\r
382                                      select localFile).ToList();\r
383 \r
384 \r
385 \r
386                 //Set the status of missing files to Conflict\r
387                 foreach (var item in filesToDelete)\r
388                 {\r
389                     //Try to acquire a gate on the file, to take into account files that have been dequeued\r
390                     //and are being processed\r
391                     using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))\r
392                     {\r
393                         if (gate.Failed)\r
394                             continue;\r
395                         StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);\r
396                     }\r
397                 }\r
398                 UpdateStatus(PithosStatus.HasConflicts);\r
399                 StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted", filesToDelete.Count));\r
400                 StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count), TraceLevel.Info);\r
401             }\r
402             else\r
403             {\r
404                 var deletedFiles = new List<FileSystemInfo>();\r
405                 foreach (var objectInfo in cloudFiles)\r
406                 {\r
407                     Log.DebugFormat("Handle deleted [{0}]",objectInfo.Uri);\r
408                     var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);\r
409                     var item = FileAgent.GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);\r
410                     Log.DebugFormat("Will delete [{0}] for [{1}]", item.FullName,objectInfo.Uri);\r
411                     if (item.Exists)\r
412                     {\r
413                         if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)\r
414                         {\r
415                             item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;\r
416 \r
417                         }\r
418                         var directory = item as DirectoryInfo;\r
419                         if (directory!=null)\r
420                             directory.Delete(true);\r
421                         else\r
422                             item.Delete();\r
423                         Log.DebugFormat("Deleted [{0}] for [{1}]", item.FullName, objectInfo.Uri);\r
424                         DateTime lastDate;\r
425                         _lastSeen.TryRemove(item.FullName, out lastDate);\r
426                         deletedFiles.Add(item);\r
427                     }\r
428                     StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted);\r
429                 }\r
430                 Log.InfoFormat("[{0}] files were deleted",deletedFiles.Count);\r
431                 StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count), TraceLevel.Info);\r
432             }\r
433 \r
434         }\r
435 \r
436         /// <summary>\r
437         /// Creates a Sync action for each changed server file\r
438         /// </summary>\r
439         /// <param name="accountInfo"></param>\r
440         /// <param name="changes"></param>\r
441         /// <returns></returns>\r
442         private IEnumerable<CloudAction> ChangesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> changes)\r
443         {\r
444             if (changes == null)\r
445                 throw new ArgumentNullException();\r
446             Contract.EndContractBlock();\r
447             var fileAgent = FileAgent.GetFileAgent(accountInfo);\r
448 \r
449             //In order to avoid multiple iterations over the files, we iterate only once\r
450             //over the remote files\r
451             foreach (var objectInfo in changes)\r
452             {\r
453                 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);\r
454                 //If a directory object already exists, we may need to sync it\r
455                 if (fileAgent.Exists(relativePath))\r
456                 {\r
457                     var localFile = fileAgent.GetFileSystemInfo(relativePath);\r
458                     //We don't need to sync directories\r
459                     if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)\r
460                         continue;\r
461                     using (new SessionScope(FlushAction.Never))\r
462                     {\r
463                         var state = StatusKeeper.GetStateByFilePath(localFile.FullName);\r
464                         _lastSeen[localFile.FullName] = DateTime.Now;\r
465                         //Common files should be checked on a per-case basis to detect differences, which is newer\r
466 \r
467                         yield return new CloudAction(accountInfo, CloudActionType.MustSynch,\r
468                                                      localFile, objectInfo, state, accountInfo.BlockSize,\r
469                                                      accountInfo.BlockHash);\r
470                     }\r
471                 }\r
472                 else\r
473                 {\r
474                     //Remote files should be downloaded\r
475                     yield return new CloudDownloadAction(accountInfo, objectInfo);\r
476                 }\r
477             }\r
478         }\r
479 \r
480         /// <summary>\r
481         /// Creates a Local Move action for each moved server file\r
482         /// </summary>\r
483         /// <param name="accountInfo"></param>\r
484         /// <param name="moves"></param>\r
485         /// <returns></returns>\r
486         private IEnumerable<CloudAction> MovesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> moves)\r
487         {\r
488             if (moves == null)\r
489                 throw new ArgumentNullException();\r
490             Contract.EndContractBlock();\r
491             var fileAgent = FileAgent.GetFileAgent(accountInfo);\r
492 \r
493             //In order to avoid multiple iterations over the files, we iterate only once\r
494             //over the remote files\r
495             foreach (var objectInfo in moves)\r
496             {\r
497                 var previousRelativepath = objectInfo.Previous.RelativeUrlToFilePath(accountInfo.UserName);\r
498                 //If the previous file already exists, we can execute a Move operation\r
499                 if (fileAgent.Exists(previousRelativepath))\r
500                 {\r
501                     var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);\r
502                     using (new SessionScope(FlushAction.Never))\r
503                     {\r
504                         var state = StatusKeeper.GetStateByFilePath(previousFile.FullName);\r
505                         _lastSeen[previousFile.FullName] = DateTime.Now;\r
506 \r
507                         //For each moved object we need to move both the local file and update                                                \r
508                         yield return new CloudAction(accountInfo, CloudActionType.RenameLocal,\r
509                                                      previousFile, objectInfo, state, accountInfo.BlockSize,\r
510                                                      accountInfo.BlockHash);\r
511                         //For modified files, we need to download the changes as well\r
512                         if (objectInfo.Hash!=objectInfo.PreviousHash)\r
513                             yield return new CloudDownloadAction(accountInfo,objectInfo);\r
514                     }\r
515                 }\r
516                 //If the previous file does not exist, we need to download it in the new location\r
517                 else\r
518                 {\r
519                     //Remote files should be downloaded\r
520                     yield return new CloudDownloadAction(accountInfo, objectInfo);\r
521                 }\r
522             }\r
523         }\r
524 \r
525 \r
526         /// <summary>\r
527         /// Creates a download action for each new server file\r
528         /// </summary>\r
529         /// <param name="accountInfo"></param>\r
530         /// <param name="creates"></param>\r
531         /// <returns></returns>\r
532         private IEnumerable<CloudAction> CreatesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> creates)\r
533         {\r
534             if (creates == null)\r
535                 throw new ArgumentNullException();\r
536             Contract.EndContractBlock();\r
537             var fileAgent = FileAgent.GetFileAgent(accountInfo);\r
538 \r
539             //In order to avoid multiple iterations over the files, we iterate only once\r
540             //over the remote files\r
541             foreach (var objectInfo in creates)\r
542             {\r
543                 if (Log.IsDebugEnabled)\r
544                     Log.DebugFormat("[NEW INFO] {0}",objectInfo.Uri);\r
545 \r
546                 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);\r
547                 //If the object already exists, we probably have a conflict\r
548                 if (fileAgent.Exists(relativePath))\r
549                 {\r
550                     Log.DebugFormat("[SKIP EXISTING] {0}", objectInfo.Uri);\r
551                     //If a directory object already exists, we don't need to perform any other action                    \r
552                     var localFile = fileAgent.GetFileSystemInfo(relativePath);\r
553                     StatusKeeper.SetFileState(localFile.FullName, FileStatus.Conflict, FileOverlayStatus.Conflict);\r
554                 }\r
555                 else\r
556                 {\r
557                     //Remote files should be downloaded\r
558                     yield return new CloudDownloadAction(accountInfo, objectInfo);\r
559                 }\r
560             }\r
561         }\r
562 \r
563         /// <summary>\r
564         /// Notify the UI to update the visual status\r
565         /// </summary>\r
566         /// <param name="status"></param>\r
567         private void UpdateStatus(PithosStatus status)\r
568         {\r
569             try\r
570             {\r
571                 StatusNotification.SetPithosStatus(status);\r
572                 //StatusNotification.Notify(new Notification());\r
573             }\r
574             catch (Exception exc)\r
575             {\r
576                 //Failure is not critical, just log it\r
577                 Log.Warn("Error while updating status", exc);\r
578             }\r
579         }\r
580 \r
581         private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)\r
582         {\r
583             var containerPaths = from container in containers\r
584                                  let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)\r
585                                  where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)\r
586                                  select containerPath;\r
587 \r
588             foreach (var path in containerPaths)\r
589             {\r
590                 Directory.CreateDirectory(path);\r
591             }\r
592         }\r
593 \r
594         public void SetSyncUris(Uri[] uris)\r
595         {            \r
596             SelectiveUris=uris.ToList();\r
597         }\r
598 \r
599         protected List<Uri> SelectiveUris\r
600         {\r
601             get { return _selectiveUris;}\r
602             set { _selectiveUris = value; }\r
603         }\r
604 \r
605         public void AddAccount(AccountInfo accountInfo)\r
606         {\r
607             //Avoid adding a duplicate accountInfo\r
608             _accounts.TryAdd(accountInfo.UserName, accountInfo);\r
609         }\r
610 \r
611         public void RemoveAccount(AccountInfo accountInfo)\r
612         {\r
613             AccountInfo account;\r
614             _accounts.TryRemove(accountInfo.UserName,out account);\r
615             SnapshotDifferencer differencer;\r
616             _differencer.Differencers.TryRemove(accountInfo.UserName, out differencer);\r
617         }\r
618     }\r
619 }\r