2 /* -----------------------------------------------------------------------
3 * <copyright file="NetworkAgent.cs" company="GRNet">
5 * Copyright 2011-2012 GRNET S.A. All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
11 * 1. Redistributions of source code must retain the above
12 * copyright notice, this list of conditions and the following
15 * 2. Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer in the documentation and/or other materials
18 * provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
34 * The views and conclusions contained in the software and
35 * documentation are those of the authors and should not be
36 * interpreted as representing official policies, either expressed
37 * or implied, of GRNET S.A.
39 * -----------------------------------------------------------------------
43 //TODO: Now there is a UUID tag. This can be used for renames/moves
47 using System.Collections.Concurrent;
48 using System.Collections.Generic;
49 using System.ComponentModel.Composition;
50 using System.Diagnostics;
51 using System.Diagnostics.Contracts;
55 using System.Threading;
56 using System.Threading.Tasks;
57 using System.Threading.Tasks.Dataflow;
58 using Castle.ActiveRecord;
59 using Pithos.Interfaces;
63 namespace Pithos.Core.Agents
65 //TODO: Ensure all network operations use exact casing. Pithos is case sensitive
67 public class NetworkAgent
69 private Agent<CloudAction> _agent;
71 [System.ComponentModel.Composition.Import]
72 private DeleteAgent _deleteAgent=new DeleteAgent();
74 [System.ComponentModel.Composition.Import]
75 public IStatusKeeper StatusKeeper { get; set; }
77 public IStatusNotification StatusNotification { get; set; }
79 private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
81 private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
83 [System.ComponentModel.Composition.Import]
84 public IPithosSettings Settings { get; set; }
86 //The Proceed signals the poll agent that it can proceed with polling.
87 //Essentially it stops the poll agent to give priority to the network agent
88 //Initially the event is signalled because we don't need to pause
89 private readonly AsyncManualResetEvent _proceedEvent = new AsyncManualResetEvent(true);
91 public AsyncManualResetEvent ProceedEvent
93 get { return _proceedEvent; }
99 _agent = Agent<CloudAction>.Start(inbox =>
104 _deleteAgent.ProceedEvent.Wait();
105 var message = inbox.Receive();
106 var process=message.Then(Process,inbox.CancellationToken);
107 inbox.LoopAsync(process, loop);
114 private async Task Process(CloudAction action)
117 throw new ArgumentNullException("action");
118 if (action.AccountInfo==null)
119 throw new ArgumentException("The action.AccountInfo is empty","action");
120 Contract.EndContractBlock();
125 using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
127 Log.InfoFormat("[ACTION] Start Processing {0}", action);
129 var cloudFile = action.CloudFile;
130 var downloadPath = action.GetDownloadPath();
134 _proceedEvent.Reset();
135 UpdateStatus(PithosStatus.Syncing);
136 var accountInfo = action.AccountInfo;
138 if (action.Action == CloudActionType.DeleteCloud)
140 //Redirect deletes to the delete agent
141 _deleteAgent.Post((CloudDeleteAction)action);
143 if (_deleteAgent.IsDeletedFile(action))
145 //Clear the status of already deleted files to avoid reprocessing
146 if (action.LocalFile != null)
147 this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
151 switch (action.Action)
153 case CloudActionType.UploadUnconditional:
154 //Abort if the file was deleted before we reached this point
155 await UploadCloudFile(action);
157 case CloudActionType.DownloadUnconditional:
158 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
160 case CloudActionType.RenameCloud:
161 var moveAction = (CloudMoveAction)action;
162 RenameCloudFile(accountInfo, moveAction);
164 case CloudActionType.MustSynch:
165 if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
167 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
171 await SyncFiles(accountInfo, action);
176 Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
177 action.CloudFile.Name);
179 catch (WebException exc)
181 Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
183 catch (OperationCanceledException)
187 catch (DirectoryNotFoundException)
189 Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete",
190 action.Action, action.LocalFile, action.CloudFile);
191 //Post a delete action for the missing file
192 Post(new CloudDeleteAction(action));
194 catch (FileNotFoundException)
196 Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete",
197 action.Action, action.LocalFile, action.CloudFile);
198 //Post a delete action for the missing file
199 Post(new CloudDeleteAction(action));
201 catch (Exception exc)
203 Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
204 action.Action, action.LocalFile, action.CloudFile, exc);
212 UpdateStatus(PithosStatus.InSynch);
217 private void UpdateStatus(PithosStatus status)
219 StatusKeeper.SetPithosStatus(status);
220 StatusNotification.Notify(new Notification());
224 private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
226 if (accountInfo == null)
227 throw new ArgumentNullException("accountInfo");
229 throw new ArgumentNullException("action");
230 if (action.LocalFile==null)
231 throw new ArgumentException("The action's local file is not specified","action");
232 if (!Path.IsPathRooted(action.LocalFile.FullName))
233 throw new ArgumentException("The action's local file path must be absolute","action");
234 if (action.CloudFile== null)
235 throw new ArgumentException("The action's cloud file is not specified", "action");
236 Contract.EndContractBlock();
238 var localFile = action.LocalFile;
239 var cloudFile = action.CloudFile;
240 var downloadPath=action.LocalFile.GetProperCapitalization();
242 var cloudHash = cloudFile.Hash.ToLower();
243 var previousCloudHash = cloudFile.PreviousHash.ToLower();
244 var localHash = action.LocalHash.Value.ToLower();
245 var topHash = action.TopHash.Value.ToLower();
247 //At this point we know that an object has changed on the server and that a local
248 //file already exists. We need to decide whether the file has only changed on
249 //the server or there is a conflicting change on the client.
252 //Not enough to compare only the local hashes (MD5), also have to compare the tophashes
253 //If any of the hashes match, we are done
254 if ((cloudHash == localHash || cloudHash == topHash))
256 Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
260 //The hashes DON'T match. We need to sync
262 // If the previous tophash matches the local tophash, the file was only changed on the server.
263 if (localHash == previousCloudHash)
265 await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
269 //If the previous and local hash don't match, there was a local conflict
270 //that was not uploaded to the server. We have a conflict
271 ReportConflict(downloadPath);
275 private void ReportConflict(string downloadPath)
277 if (String.IsNullOrWhiteSpace(downloadPath))
278 throw new ArgumentNullException("downloadPath");
279 Contract.EndContractBlock();
281 StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
282 UpdateStatus(PithosStatus.HasConflicts);
283 var message = String.Format("Conflict detected for file {0}", downloadPath);
285 StatusNotification.NotifyChange(message, TraceLevel.Warning);
288 public void Post(CloudAction cloudAction)
290 if (cloudAction == null)
291 throw new ArgumentNullException("cloudAction");
292 if (cloudAction.AccountInfo==null)
293 throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
294 Contract.EndContractBlock();
296 _deleteAgent.ProceedEvent.Wait();
298 //If the action targets a local file, add a treehash calculation
299 if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
301 var accountInfo = cloudAction.AccountInfo;
302 var localFile = (FileInfo) cloudAction.LocalFile;
303 if (localFile.Length > accountInfo.BlockSize)
304 cloudAction.TopHash =
305 new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
306 accountInfo.BlockSize,
307 accountInfo.BlockHash, Settings.HashingParallelism).Result
308 .TopHash.ToHashString());
311 cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
316 //The hash for a directory is the empty string
317 cloudAction.TopHash = new Lazy<string>(() => String.Empty);
320 if (cloudAction is CloudDeleteAction)
321 _deleteAgent.Post((CloudDeleteAction)cloudAction);
323 _agent.Post(cloudAction);
327 public IEnumerable<CloudAction> GetEnumerable()
329 return _agent.GetEnumerable();
332 public Task GetDeleteAwaiter()
334 return _deleteAgent.ProceedEvent.WaitAsync();
336 public CancellationToken CancellationToken
338 get { return _agent.CancellationToken; }
341 private static FileAgent GetFileAgent(AccountInfo accountInfo)
343 return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
348 private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
350 if (accountInfo==null)
351 throw new ArgumentNullException("accountInfo");
353 throw new ArgumentNullException("action");
354 if (action.CloudFile==null)
355 throw new ArgumentException("CloudFile","action");
356 if (action.LocalFile==null)
357 throw new ArgumentException("LocalFile","action");
358 if (action.OldLocalFile==null)
359 throw new ArgumentException("OldLocalFile","action");
360 if (action.OldCloudFile==null)
361 throw new ArgumentException("OldCloudFile","action");
362 Contract.EndContractBlock();
365 var newFilePath = action.LocalFile.FullName;
367 //How do we handle concurrent renames and deletes/uploads/downloads?
368 //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
369 // This should never happen as the network agent executes only one action at a time
370 //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
371 // the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the
372 // same name will fail.
373 // This should never happen as the network agent executes only one action at a time.
374 //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
375 // to remove the rename from the queue.
376 // We can probably ignore this case. It will result in an error which should be ignored
379 //The local file is already renamed
380 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
383 var account = action.CloudFile.Account ?? accountInfo.UserName;
384 var container = action.CloudFile.Container;
386 var client = new CloudFilesClient(accountInfo);
387 //TODO: What code is returned when the source file doesn't exist?
388 client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
390 StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
391 StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
392 NativeMethods.RaiseChangeNotification(newFilePath);
396 private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
398 if (accountInfo == null)
399 throw new ArgumentNullException("accountInfo");
400 if (cloudFile == null)
401 throw new ArgumentNullException("cloudFile");
402 if (String.IsNullOrWhiteSpace(cloudFile.Account))
403 throw new ArgumentNullException("cloudFile");
404 if (String.IsNullOrWhiteSpace(cloudFile.Container))
405 throw new ArgumentNullException("cloudFile");
406 if (String.IsNullOrWhiteSpace(filePath))
407 throw new ArgumentNullException("filePath");
408 if (!Path.IsPathRooted(filePath))
409 throw new ArgumentException("The filePath must be rooted", "filePath");
410 Contract.EndContractBlock();
413 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
414 var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
416 var url = relativeUrl.ToString();
417 if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
421 //Are we already downloading or uploading the file?
422 using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
427 var client = new CloudFilesClient(accountInfo);
428 var account = cloudFile.Account;
429 var container = cloudFile.Container;
431 if (cloudFile.Content_Type == @"application/directory")
433 if (!Directory.Exists(localPath))
434 Directory.CreateDirectory(localPath);
438 //Retrieve the hashmap from the server
439 var serverHash = await client.GetHashMap(account, container, url);
440 //If it's a small file
441 if (serverHash.Hashes.Count == 1)
442 //Download it in one go
444 DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
445 //Otherwise download it block by block
447 await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
449 if (cloudFile.AllowedTo == "read")
451 var attributes = File.GetAttributes(localPath);
452 File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);
456 //Now we can store the object's metadata without worrying about ghost status entries
457 StatusKeeper.StoreInfo(localPath, cloudFile);
462 //Download a small file with a single GET operation
463 private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
466 throw new ArgumentNullException("client");
468 throw new ArgumentNullException("cloudFile");
469 if (relativeUrl == null)
470 throw new ArgumentNullException("relativeUrl");
471 if (String.IsNullOrWhiteSpace(filePath))
472 throw new ArgumentNullException("filePath");
473 if (!Path.IsPathRooted(filePath))
474 throw new ArgumentException("The localPath must be rooted", "filePath");
475 Contract.EndContractBlock();
477 var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
478 //If the file already exists
479 if (File.Exists(localPath))
481 //First check with MD5 as this is a small file
482 var localMD5 = Signature.CalculateMD5(localPath);
483 var cloudHash=serverHash.TopHash.ToHashString();
484 if (localMD5==cloudHash)
486 //Then check with a treehash
487 var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
488 var localHash = localTreeHash.TopHash.ToHashString();
489 if (localHash==cloudHash)
492 StatusNotification.Notify(new CloudNotification { Data = cloudFile });
494 var fileAgent = GetFileAgent(accountInfo);
495 //Calculate the relative file path for the new file
496 var relativePath = relativeUrl.RelativeUriToFilePath();
497 //The file will be stored in a temporary location while downloading with an extension .download
498 var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
499 //Make sure the target folder exists. DownloadFileTask will not create the folder
500 var tempFolder = Path.GetDirectoryName(tempPath);
501 if (!Directory.Exists(tempFolder))
502 Directory.CreateDirectory(tempFolder);
504 //Download the object to the temporary location
505 await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
507 //Create the local folder if it doesn't exist (necessary for shared objects)
508 var localFolder = Path.GetDirectoryName(localPath);
509 if (!Directory.Exists(localFolder))
510 Directory.CreateDirectory(localFolder);
511 //And move it to its actual location once downloading is finished
512 if (File.Exists(localPath))
513 File.Replace(tempPath,localPath,null,true);
515 File.Move(tempPath,localPath);
516 //Notify listeners that a local file has changed
517 StatusNotification.NotifyChangedFile(localPath);
522 //Download a file asynchronously using blocks
523 public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
526 throw new ArgumentNullException("client");
527 if (cloudFile == null)
528 throw new ArgumentNullException("cloudFile");
529 if (relativeUrl == null)
530 throw new ArgumentNullException("relativeUrl");
531 if (String.IsNullOrWhiteSpace(filePath))
532 throw new ArgumentNullException("filePath");
533 if (!Path.IsPathRooted(filePath))
534 throw new ArgumentException("The filePath must be rooted", "filePath");
535 if (serverHash == null)
536 throw new ArgumentNullException("serverHash");
537 Contract.EndContractBlock();
539 var fileAgent = GetFileAgent(accountInfo);
540 var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
542 //Calculate the relative file path for the new file
543 var relativePath = relativeUrl.RelativeUriToFilePath();
544 var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
548 //Calculate the file's treehash
549 var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
551 //And compare it with the server's hash
552 var upHashes = serverHash.GetHashesAsStrings();
553 var localHashes = treeHash.HashDictionary;
554 for (int i = 0; i < upHashes.Length; i++)
556 //For every non-matching hash
557 var upHash = upHashes[i];
558 if (!localHashes.ContainsKey(upHash))
560 StatusNotification.Notify(new CloudNotification { Data = cloudFile });
562 if (blockUpdater.UseOrphan(i, upHash))
564 Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
567 Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
568 var start = i*serverHash.BlockSize;
569 //To download the last block just pass a null for the end of the range
571 if (i < upHashes.Length - 1 )
572 end= ((i + 1)*serverHash.BlockSize) ;
574 //Download the missing block
575 var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
578 blockUpdater.StoreBlock(i, block);
581 Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
585 //Want to avoid notifications if no changes were made
586 var hasChanges = blockUpdater.HasBlocks;
587 blockUpdater.Commit();
590 //Notify listeners that a local file has changed
591 StatusNotification.NotifyChangedFile(localPath);
593 Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);
597 private async Task UploadCloudFile(CloudAction action)
600 throw new ArgumentNullException("action");
601 Contract.EndContractBlock();
605 var accountInfo = action.AccountInfo;
607 var fileInfo = action.LocalFile;
609 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
612 var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
613 if (relativePath.StartsWith(FolderConstants.OthersFolder))
615 var parts = relativePath.Split('\\');
616 var accountName = parts[1];
617 var oldName = accountInfo.UserName;
618 var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
619 var nameIndex = absoluteUri.IndexOf(oldName);
620 var root = absoluteUri.Substring(0, nameIndex);
622 accountInfo = new AccountInfo
624 UserName = accountName,
625 AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
626 StorageUri = new Uri(root + accountName),
627 BlockHash = accountInfo.BlockHash,
628 BlockSize = accountInfo.BlockSize,
629 Token = accountInfo.Token
634 var fullFileName = fileInfo.GetProperCapitalization();
635 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
637 //Abort if the file is already being uploaded or downloaded
641 var cloudFile = action.CloudFile;
642 var account = cloudFile.Account ?? accountInfo.UserName;
644 var client = new CloudFilesClient(accountInfo);
645 //Even if GetObjectInfo times out, we can proceed with the upload
646 var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
648 //If this is a read-only file, do not upload changes
649 if (info.AllowedTo == "read")
652 //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
653 if (fileInfo is DirectoryInfo)
655 //If the directory doesn't exist the Hash property will be empty
656 if (String.IsNullOrWhiteSpace(info.Hash))
657 //Go on and create the directory
658 await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
663 var cloudHash = info.Hash.ToLower();
665 var hash = action.LocalHash.Value;
666 var topHash = action.TopHash.Value;
668 //If the file hashes match, abort the upload
669 if (hash == cloudHash || topHash == cloudHash)
671 //but store any metadata changes
672 StatusKeeper.StoreInfo(fullFileName, info);
673 Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
678 //Mark the file as modified while we upload it
679 StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
682 //Upload even small files using the Hashmap. The server may already contain
685 //First, calculate the tree hash
686 var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
687 accountInfo.BlockHash, 2);
689 await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
691 //If everything succeeds, change the file and overlay status to normal
692 StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
694 //Notify the Shell to update the overlays
695 NativeMethods.RaiseChangeNotification(fullFileName);
696 StatusNotification.NotifyChangedFile(fullFileName);
698 catch (AggregateException ex)
700 var exc = ex.InnerException as WebException;
702 throw ex.InnerException;
703 if (HandleUploadWebException(action, exc))
707 catch (WebException ex)
709 if (HandleUploadWebException(action, ex))
715 Log.Error("Unexpected error while uploading file", ex);
723 private bool HandleUploadWebException(CloudAction action, WebException exc)
725 var response = exc.Response as HttpWebResponse;
726 if (response == null)
728 if (response.StatusCode == HttpStatusCode.Unauthorized)
730 Log.Error("Not allowed to upload file", exc);
731 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
732 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
733 StatusNotification.NotifyChange(message, TraceLevel.Warning);
739 public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
741 if (accountInfo == null)
742 throw new ArgumentNullException("accountInfo");
744 throw new ArgumentNullException("cloudFile");
745 if (fileInfo == null)
746 throw new ArgumentNullException("fileInfo");
747 if (String.IsNullOrWhiteSpace(url))
748 throw new ArgumentNullException(url);
750 throw new ArgumentNullException("treeHash");
751 if (String.IsNullOrWhiteSpace(cloudFile.Container) )
752 throw new ArgumentException("Invalid container","cloudFile");
753 Contract.EndContractBlock();
755 var fullFileName = fileInfo.GetProperCapitalization();
757 var account = cloudFile.Account ?? accountInfo.UserName;
758 var container = cloudFile.Container ;
760 var client = new CloudFilesClient(accountInfo);
761 //Send the hashmap to the server
762 var missingHashes = await client.PutHashMap(account, container, url, treeHash);
763 //If the server returns no missing hashes, we are done
764 while (missingHashes.Count > 0)
767 var buffer = new byte[accountInfo.BlockSize];
768 foreach (var missingHash in missingHashes)
770 //Find the proper block
771 var blockIndex = treeHash.HashDictionary[missingHash];
772 var offset = blockIndex*accountInfo.BlockSize;
774 var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
778 //And upload the block
779 await client.PostBlock(account, container, buffer, 0, read);
780 Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
782 catch (Exception exc)
784 Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
789 //Repeat until there are no more missing hashes
790 missingHashes = await client.PutHashMap(account, container, url, treeHash);
795 public void AddAccount(AccountInfo accountInfo)
797 if (!_accounts.Contains(accountInfo))
798 _accounts.Add(accountInfo);