2 /* -----------------------------------------------------------------------
\r
3 * <copyright file="PollAgent.cs" company="GRNet">
\r
5 * Copyright 2011-2012 GRNET S.A. All rights reserved.
\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
11 * 1. Redistributions of source code must retain the above
\r
12 * copyright notice, this list of conditions and the following
\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
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
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
39 * -----------------------------------------------------------------------
\r
43 using System.Collections.Concurrent;
\r
44 using System.ComponentModel.Composition;
\r
45 using System.Diagnostics;
\r
46 using System.Diagnostics.Contracts;
\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
56 namespace Pithos.Core.Agents
\r
59 using System.Collections.Generic;
\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
69 public class PollAgent
\r
71 private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
\r
73 [System.ComponentModel.Composition.Import]
\r
74 public IStatusKeeper StatusKeeper { get; set; }
\r
76 [System.ComponentModel.Composition.Import]
\r
77 public IPithosSettings Settings { get; set; }
\r
79 [System.ComponentModel.Composition.Import]
\r
80 public NetworkAgent NetworkAgent { get; set; }
\r
82 public IStatusNotification StatusNotification { get; set; }
\r
84 private bool _firstPoll = true;
\r
86 //The Sync Event signals a manual synchronisation
\r
87 private readonly AsyncManualResetEvent _syncEvent = new AsyncManualResetEvent();
\r
89 private readonly ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();
\r
90 private readonly ConcurrentDictionary<Uri, AccountInfo> _accounts = new ConcurrentDictionary<Uri,AccountInfo>();
\r
94 /// Start a manual synchronization
\r
96 public void SynchNow()
\r
102 /// Remote files are polled periodically. Any changes are processed
\r
104 /// <param name="since"></param>
\r
105 /// <returns></returns>
\r
106 public async Task PollRemoteFiles(DateTime? since = null)
\r
108 if (Log.IsDebugEnabled)
\r
109 Log.DebugFormat("Polling changes after [{0}]",since);
\r
111 Debug.Assert(Thread.CurrentThread.IsBackground, "Polling Ended up in the main thread!");
\r
114 using (ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
\r
116 //If this poll fails, we will retry with the same since value
\r
117 var nextSince = since;
\r
120 UpdateStatus(PithosStatus.PollSyncing);
\r
122 var tasks = from accountInfo in _accounts.Values
\r
123 select ProcessAccountFiles(accountInfo, since);
\r
125 var nextTimes=await TaskEx.WhenAll(tasks.ToList());
\r
127 _firstPoll = false;
\r
128 //Reschedule the poll with the current timestamp as a "since" value
\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
135 catch (Exception ex)
\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
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
147 //Wait for the polling interval to pass or the Sync event to be signalled
\r
148 nextSince = await WaitForScheduledOrManualPoll(nextSince);
\r
152 //Ensure polling is scheduled even in case of error
\r
153 TaskEx.Run(() => PollRemoteFiles(nextSince));
\r
159 /// Wait for the polling period to expire or a manual sync request
\r
161 /// <param name="since"></param>
\r
162 /// <returns></returns>
\r
163 private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
\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
169 //Wait for network processing to finish before polling
\r
170 var pauseTask=NetworkAgent.ProceedEvent.WaitAsync();
\r
171 await TaskEx.WhenAll(signaledTask, pauseTask);
\r
173 //If polling is signalled by SynchNow, ignore the since tag
\r
174 if (sync.IsCompleted)
\r
176 //TODO: Must convert to AutoReset
\r
177 _syncEvent.Reset();
\r
183 public async Task<DateTime?> ProcessAccountFiles(AccountInfo accountInfo, DateTime? since = null)
\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
192 using (ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
\r
195 await NetworkAgent.GetDeleteAwaiter();
\r
197 Log.Info("Scheduled");
\r
198 var client = new CloudFilesClient(accountInfo);
\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
206 CreateContainerFolders(accountInfo, containers);
\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
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
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
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
231 using (ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
\r
233 var dict = listTasks.ToDictionary(t => t.AsyncState);
\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
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
245 var sharedObjects = dict["shared"].Result;
\r
246 nextSince = GetLatestDateBefore(nextSince, sharedObjects);
\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
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
258 !remoteObjects.Any(
\r
259 info => info.Name == trash.Name && info.Hash == trash.Hash)
\r
261 ProcessTrashedFiles(accountInfo, realTrash);
\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
272 StatusKeeper.CleanupOrphanStates();
\r
273 StatusKeeper.CleanupStaleStates(accountInfo, cleanRemotes);
\r
275 var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);
\r
277 var filterUris = SelectiveUris[accountInfo.AccountKey];
\r
279 ProcessDeletedFiles(accountInfo, differencer.Deleted.FilterDirectlyBelow(filterUris));
\r
281 // @@@ NEED To add previous state here as well, To compare with previous hash
\r
285 //Create a list of actions from the remote files
\r
287 var allActions = MovesToActions(accountInfo,differencer.Moved.FilterDirectlyBelow(filterUris))
\r
289 ChangesToActions(accountInfo, differencer.Changed.FilterDirectlyBelow(filterUris)))
\r
291 CreatesToActions(accountInfo, differencer.Created.FilterDirectlyBelow(filterUris)));
\r
293 //And remove those that are already being processed by the agent
\r
294 var distinctActions = allActions
\r
295 .Except(NetworkAgent.GetEnumerable(), new LocalFileComparer())
\r
298 //Queue all the actions
\r
299 foreach (var message in distinctActions)
\r
301 NetworkAgent.Post(message);
\r
304 Log.Info("[LISTENER] End Processing");
\r
307 catch (Exception ex)
\r
309 Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
\r
313 Log.Info("[LISTENER] Finished");
\r
319 /// Returns the latest LastModified date from the list of objects, but only if it is before
\r
320 /// than the threshold value
\r
322 /// <param name="threshold"></param>
\r
323 /// <param name="cloudObjects"></param>
\r
324 /// <returns></returns>
\r
325 private static DateTime? GetLatestDateBefore(DateTime? threshold, IList<ObjectInfo> cloudObjects)
\r
327 DateTime? maxDate = null;
\r
328 if (cloudObjects!=null && cloudObjects.Count > 0)
\r
329 maxDate = cloudObjects.Max(obj => obj.Last_Modified);
\r
330 if (maxDate == null || maxDate == DateTime.MinValue)
\r
332 if (threshold == null || threshold == DateTime.MinValue || threshold > maxDate)
\r
338 /// Returns the latest LastModified date from the list of objects, but only if it is after
\r
339 /// the threshold value
\r
341 /// <param name="threshold"></param>
\r
342 /// <param name="cloudObjects"></param>
\r
343 /// <returns></returns>
\r
344 private static DateTime? GetLatestDateAfter(DateTime? threshold, IList<ObjectInfo> cloudObjects)
\r
346 DateTime? maxDate = null;
\r
347 if (cloudObjects!=null && cloudObjects.Count > 0)
\r
348 maxDate = cloudObjects.Max(obj => obj.Last_Modified);
\r
349 if (maxDate == null || maxDate == DateTime.MinValue)
\r
351 if (threshold == null || threshold == DateTime.MinValue || threshold < maxDate)
\r
356 readonly AccountsDifferencer _differencer = new AccountsDifferencer();
\r
357 private Dictionary<Uri, List<Uri>> _selectiveUris = new Dictionary<Uri, List<Uri>>();
\r
360 /// Deletes local files that are not found in the list of cloud files
\r
362 /// <param name="accountInfo"></param>
\r
363 /// <param name="cloudFiles"></param>
\r
364 private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles)
\r
366 if (accountInfo == null)
\r
367 throw new ArgumentNullException("accountInfo");
\r
368 if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
\r
369 throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
\r
370 if (cloudFiles == null)
\r
371 throw new ArgumentNullException("cloudFiles");
\r
372 Contract.EndContractBlock();
\r
377 //Only consider files that are not being modified, ie they are in the Unchanged state
\r
378 var deleteCandidates = FileState.Queryable.Where(state =>
\r
379 state.FilePath.StartsWith(accountInfo.AccountPath)
\r
380 && state.FileStatus == FileStatus.Unchanged).ToList();
\r
383 //TODO: filesToDelete must take into account the Others container
\r
384 var filesToDelete = (from deleteCandidate in deleteCandidates
\r
385 let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
\r
386 let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
\r
388 !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)
\r
389 select localFile).ToList();
\r
393 //Set the status of missing files to Conflict
\r
394 foreach (var item in filesToDelete)
\r
396 //Try to acquire a gate on the file, to take into account files that have been dequeued
\r
397 //and are being processed
\r
398 using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
\r
402 StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted,"Local file missing from server");
\r
405 UpdateStatus(PithosStatus.HasConflicts);
\r
406 StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted", filesToDelete.Count));
\r
407 StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count), TraceLevel.Info);
\r
411 var deletedFiles = new List<FileSystemInfo>();
\r
412 foreach (var objectInfo in cloudFiles)
\r
414 if (Log.IsDebugEnabled)
\r
415 Log.DebugFormat("Handle deleted [{0}]",objectInfo.Uri);
\r
416 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
\r
417 var item = FileAgent.GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);
\r
418 if (Log.IsDebugEnabled)
\r
419 Log.DebugFormat("Will delete [{0}] for [{1}]", item.FullName,objectInfo.Uri);
\r
422 if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
\r
424 item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
\r
429 Log.DebugFormat("Deleting {0}", item.FullName);
\r
431 var directory = item as DirectoryInfo;
\r
432 if (directory!=null)
\r
433 directory.Delete(true);
\r
436 Log.DebugFormat("Deleted [{0}] for [{1}]", item.FullName, objectInfo.Uri);
\r
438 _lastSeen.TryRemove(item.FullName, out lastDate);
\r
439 deletedFiles.Add(item);
\r
441 StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted, "File Deleted");
\r
443 Log.InfoFormat("[{0}] files were deleted",deletedFiles.Count);
\r
444 StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count), TraceLevel.Info);
\r
450 /// Creates a Sync action for each changed server file
\r
452 /// <param name="accountInfo"></param>
\r
453 /// <param name="changes"></param>
\r
454 /// <returns></returns>
\r
455 private IEnumerable<CloudAction> ChangesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> changes)
\r
457 if (changes == null)
\r
458 throw new ArgumentNullException();
\r
459 Contract.EndContractBlock();
\r
460 var fileAgent = FileAgent.GetFileAgent(accountInfo);
\r
462 //In order to avoid multiple iterations over the files, we iterate only once
\r
463 //over the remote files
\r
464 foreach (var objectInfo in changes)
\r
466 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
\r
467 //If a directory object already exists, we may need to sync it
\r
468 if (fileAgent.Exists(relativePath))
\r
470 var localFile = fileAgent.GetFileSystemInfo(relativePath);
\r
471 //We don't need to sync directories
\r
472 if (objectInfo.IsDirectory && localFile is DirectoryInfo)
\r
474 using (new SessionScope(FlushAction.Never))
\r
476 var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
\r
477 _lastSeen[localFile.FullName] = DateTime.Now;
\r
478 //Common files should be checked on a per-case basis to detect differences, which is newer
\r
480 yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
\r
481 localFile, objectInfo, state, accountInfo.BlockSize,
\r
482 accountInfo.BlockHash);
\r
487 //Remote files should be downloaded
\r
488 yield return new CloudDownloadAction(accountInfo, objectInfo);
\r
494 /// Creates a Local Move action for each moved server file
\r
496 /// <param name="accountInfo"></param>
\r
497 /// <param name="moves"></param>
\r
498 /// <returns></returns>
\r
499 private IEnumerable<CloudAction> MovesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> moves)
\r
502 throw new ArgumentNullException();
\r
503 Contract.EndContractBlock();
\r
504 var fileAgent = FileAgent.GetFileAgent(accountInfo);
\r
506 //In order to avoid multiple iterations over the files, we iterate only once
\r
507 //over the remote files
\r
508 foreach (var objectInfo in moves)
\r
510 var previousRelativepath = objectInfo.Previous.RelativeUrlToFilePath(accountInfo.UserName);
\r
511 //If the previous file already exists, we can execute a Move operation
\r
512 if (fileAgent.Exists(previousRelativepath))
\r
514 var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
\r
515 using (new SessionScope(FlushAction.Never))
\r
517 var state = StatusKeeper.GetStateByFilePath(previousFile.FullName);
\r
518 _lastSeen[previousFile.FullName] = DateTime.Now;
\r
520 //For each moved object we need to move both the local file and update
\r
521 yield return new CloudAction(accountInfo, CloudActionType.RenameLocal,
\r
522 previousFile, objectInfo, state, accountInfo.BlockSize,
\r
523 accountInfo.BlockHash);
\r
524 //For modified files, we need to download the changes as well
\r
525 if (objectInfo.Hash!=objectInfo.PreviousHash)
\r
526 yield return new CloudDownloadAction(accountInfo,objectInfo);
\r
529 //If the previous file does not exist, we need to download it in the new location
\r
532 //Remote files should be downloaded
\r
533 yield return new CloudDownloadAction(accountInfo, objectInfo);
\r
540 /// Creates a download action for each new server file
\r
542 /// <param name="accountInfo"></param>
\r
543 /// <param name="creates"></param>
\r
544 /// <returns></returns>
\r
545 private IEnumerable<CloudAction> CreatesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> creates)
\r
547 if (creates == null)
\r
548 throw new ArgumentNullException();
\r
549 Contract.EndContractBlock();
\r
550 var fileAgent = FileAgent.GetFileAgent(accountInfo);
\r
552 //In order to avoid multiple iterations over the files, we iterate only once
\r
553 //over the remote files
\r
554 foreach (var objectInfo in creates)
\r
556 if (Log.IsDebugEnabled)
\r
557 Log.DebugFormat("[NEW INFO] {0}",objectInfo.Uri);
\r
559 var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
\r
561 //If the object already exists, we should check before uploading or downloading
\r
562 if (fileAgent.Exists(relativePath))
\r
564 var localFile= fileAgent.GetFileSystemInfo(relativePath);
\r
565 var state = StatusKeeper.GetStateByFilePath(localFile.WithProperCapitalization().FullName);
\r
566 yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
\r
567 localFile, objectInfo, state, accountInfo.BlockSize,
\r
568 accountInfo.BlockHash);
\r
572 //Remote files should be downloaded
\r
573 yield return new CloudDownloadAction(accountInfo, objectInfo);
\r
580 /// Notify the UI to update the visual status
\r
582 /// <param name="status"></param>
\r
583 private void UpdateStatus(PithosStatus status)
\r
587 StatusNotification.SetPithosStatus(status);
\r
588 //StatusNotification.Notify(new Notification());
\r
590 catch (Exception exc)
\r
592 //Failure is not critical, just log it
\r
593 Log.Warn("Error while updating status", exc);
\r
597 private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
\r
599 var containerPaths = from container in containers
\r
600 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
\r
601 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
\r
602 select containerPath;
\r
604 foreach (var path in containerPaths)
\r
606 Directory.CreateDirectory(path);
\r
610 public void SetSyncUris(Uri accountKey, Uri[] uris)
\r
612 SelectiveUris[accountKey]=uris.ToList();
\r
615 protected Dictionary<Uri,List<Uri>> SelectiveUris
\r
617 get { return _selectiveUris;}
\r
618 set { _selectiveUris = value; }
\r
621 public void AddAccount(AccountInfo accountInfo)
\r
623 //Avoid adding a duplicate accountInfo
\r
624 _accounts.TryAdd(accountInfo.AccountKey, accountInfo);
\r
627 public void RemoveAccount(AccountInfo accountInfo)
\r
629 AccountInfo account;
\r
630 _accounts.TryRemove(accountInfo.AccountKey, out account);
\r
631 SnapshotDifferencer differencer;
\r
632 _differencer.Differencers.TryRemove(accountInfo.AccountKey, out differencer);
\r
635 public void SetSelectivePaths(AccountInfo accountInfo,Uri[] added, Uri[] removed)
\r
637 AbortRemovedPaths(accountInfo,removed);
\r
638 DownloadNewPaths(accountInfo,added);
\r
641 private void DownloadNewPaths(AccountInfo accountInfo, Uri[] added)
\r
643 var client = new CloudFilesClient(accountInfo);
\r
644 foreach (var folderUri in added)
\r
648 var segmentsCount = folderUri.Segments.Length;
\r
649 if (segmentsCount < 3)
\r
651 if (segmentsCount==3)
\r
653 account = folderUri.Segments[1].TrimEnd('/');
\r
654 container = folderUri.Segments[2].TrimEnd('/');
\r
658 account = folderUri.Segments[2].TrimEnd('/');
\r
659 container = folderUri.Segments[3].TrimEnd('/');
\r
661 IList<ObjectInfo> items;
\r
662 if(segmentsCount>3)
\r
664 var folder =String.Join("", folderUri.Segments.Splice(4));
\r
665 items = client.ListObjects(account, container, folder);
\r
669 items = client.ListObjects(account, container);
\r
671 var actions=CreatesToActions(accountInfo, items);
\r
672 foreach (var action in actions)
\r
674 NetworkAgent.Post(action);
\r
678 //Need to get a listing of each of the URLs, then post them to the NetworkAgent
\r
679 //CreatesToActions(accountInfo,)
\r
681 /* NetworkAgent.Post();*/
\r
684 private void AbortRemovedPaths(AccountInfo accountInfo, Uri[] removed)
\r
686 /*this.NetworkAgent.*/
\r