2 using System.Collections.Generic;
\r
3 using System.ComponentModel.Composition;
\r
4 using System.Diagnostics;
\r
5 using System.Diagnostics.Contracts;
\r
9 using System.Reflection;
\r
10 using System.Security.Cryptography;
\r
11 using System.Threading;
\r
12 using System.Threading.Tasks;
\r
13 using Pithos.Interfaces;
\r
14 using Pithos.Network;
\r
17 namespace Pithos.Core.Agents
\r
19 [Export(typeof(Uploader))]
\r
20 public class Uploader
\r
22 private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
\r
25 private IStatusKeeper StatusKeeper { get; set; }
\r
27 public IStatusNotification StatusNotification { get; set; }
\r
30 //CancellationTokenSource _cts = new CancellationTokenSource();
\r
31 /*public void SignalStop()
\r
36 public async Task UploadCloudFile(CloudUploadAction action,CancellationToken cancellationToken)
\r
39 throw new ArgumentNullException("action");
\r
40 Contract.EndContractBlock();
\r
42 using (ThreadContext.Stacks["Operation"].Push("UploadCloudFile"))
\r
46 await UnpauseEvent.WaitAsync();
\r
48 var fileInfo = action.LocalFile;
\r
50 if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
\r
53 if (!Selectives.IsSelected(action.AccountInfo, fileInfo) && !action.IsCreation)
\r
56 //Try to load the action's local state, if it is empty
\r
57 if (action.FileState == null)
\r
58 action.FileState = StatusKeeper.GetStateByFilePath(fileInfo.FullName);
\r
59 if (action.FileState != null)
\r
62 Log.WarnFormat("File [{0}] has no local state. It was probably created by a download action", fileInfo.FullName);
\r
67 var latestState = action.FileState;
\r
69 //Do not upload files in conflict
\r
70 if (latestState.FileStatus == FileStatus.Conflict)
\r
72 Log.InfoFormat("Skipping file in conflict [{0}]", fileInfo.FullName);
\r
75 //Do not upload files when we have no permission
\r
76 if (latestState.FileStatus == FileStatus.Forbidden)
\r
78 Log.InfoFormat("Skipping forbidden file [{0}]", fileInfo.FullName);
\r
82 //Are we targeting our own account or a sharer account?
\r
83 var relativePath = fileInfo.AsRelativeTo(action.AccountInfo.AccountPath);
\r
84 var accountInfo = relativePath.StartsWith(FolderConstants.OthersFolder)
\r
85 ? GetSharerAccount(relativePath, action.AccountInfo)
\r
86 : action.AccountInfo;
\r
90 var fullFileName = fileInfo.GetProperCapitalization();
\r
91 using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
\r
93 //Abort if the file is already being uploaded or downloaded
\r
97 var cloudFile = action.CloudFile;
\r
98 var account = cloudFile.Account ?? accountInfo.UserName;
\r
102 var client = new CloudFilesClient(accountInfo);
\r
104 //Even if GetObjectInfo times out, we can proceed with the upload
\r
105 var cloudInfo = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
\r
107 //If this a shared file
\r
108 if (!cloudFile.Account.Equals(action.AccountInfo.UserName,StringComparison.InvariantCultureIgnoreCase))
\r
112 if (!cloudInfo.IsWritable(action.AccountInfo.UserName))
\r
114 MakeFileReadOnly(fullFileName);
\r
115 StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal, "");
\r
120 //If this is a read-only file, do not upload changes
\r
121 if ( !cloudInfo.IsWritable(action.AccountInfo.UserName) ||
\r
122 //If the file is new, but we can't upload it
\r
123 (!cloudInfo.Exists && !client.CanUpload(account, cloudFile)) )
\r
125 MakeFileReadOnly(fullFileName);
\r
126 StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal, "");
\r
132 await UnpauseEvent.WaitAsync();
\r
134 if (fileInfo is DirectoryInfo)
\r
136 //If the directory doesn't exist the Hash property will be empty
\r
137 if (String.IsNullOrWhiteSpace(cloudInfo.X_Object_Hash))
\r
138 //Go on and create the directory
\r
139 await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName,
\r
140 String.Empty, "application/directory");
\r
141 //If the upload is in response to a Folder create with Selective Sync enabled
\r
142 if (action.IsCreation)
\r
144 //Add the folder to the Selected URls
\r
145 var selectiveUri = new Uri(client.RootAddressUri, cloudFile.Uri);
\r
146 Selectives.AddUri(accountInfo, selectiveUri);
\r
147 Selectives.Save(accountInfo);
\r
153 var cloudHash = cloudInfo.X_Object_Hash.ToLower();
\r
157 using(StatusNotification.GetNotifier("Hashing {0} for Upload", "Finished hashing {0}",fileInfo.Name))
\r
159 treeHash = action.TreeHash.Value;
\r
160 topHash = treeHash.TopHash.ToHashString();
\r
165 //If the file hashes match, abort the upload
\r
166 if (cloudInfo != ObjectInfo.Empty && (topHash == cloudHash ))
\r
168 //but store any metadata changes
\r
169 StatusKeeper.StoreInfo(fullFileName, cloudInfo);
\r
170 Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
\r
175 //Mark the file as modified while we upload it
\r
176 await StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
\r
177 //And then upload it
\r
179 //Upload even small files using the Hashmap. The server may already contain
\r
180 //the relevant block
\r
184 await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash,cancellationToken);
\r
186 //If everything succeeds, change the file and overlay status to normal
\r
187 StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal, "");
\r
189 catch (WebException exc)
\r
191 var response = (exc.Response as HttpWebResponse);
\r
192 if (response == null)
\r
194 if (response.StatusCode == HttpStatusCode.Forbidden)
\r
196 StatusKeeper.SetFileState(fileInfo.FullName, FileStatus.Forbidden, FileOverlayStatus.Conflict, "Forbidden");
\r
197 MakeFileReadOnly(fullFileName);
\r
200 //In any other case, propagate the error
\r
204 //Notify the Shell to update the overlays
\r
205 NativeMethods.RaiseChangeNotification(fullFileName);
\r
206 StatusNotification.NotifyChangedFile(fullFileName);
\r
208 catch (AggregateException ex)
\r
210 var exc = ex.InnerException as WebException;
\r
212 throw ex.InnerException;
\r
213 if (HandleUploadWebException(action, exc))
\r
217 catch (WebException ex)
\r
219 if (HandleUploadWebException(action, ex))
\r
223 catch (Exception ex)
\r
225 Log.Error("Unexpected error while uploading file", ex);
\r
231 private static void MakeFileReadOnly(string fullFileName)
\r
233 var attributes = File.GetAttributes(fullFileName);
\r
234 //Do not make any modifications if not necessary
\r
235 if (attributes.HasFlag(FileAttributes.ReadOnly))
\r
237 File.SetAttributes(fullFileName, attributes | FileAttributes.ReadOnly);
\r
240 private static AccountInfo GetSharerAccount(string relativePath, AccountInfo accountInfo)
\r
242 var parts = relativePath.Split('\\');
\r
243 var accountName = parts[1];
\r
244 var oldName = accountInfo.UserName;
\r
245 var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
\r
246 var nameIndex = absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
\r
247 var root = absoluteUri.Substring(0, nameIndex);
\r
249 accountInfo = new AccountInfo
\r
251 UserName = accountName,
\r
252 AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
\r
253 StorageUri = new Uri(root + accountName),
\r
254 BlockHash = accountInfo.BlockHash,
\r
255 BlockSize = accountInfo.BlockSize,
\r
256 Token = accountInfo.Token
\r
258 return accountInfo;
\r
262 public async Task UploadWithHashMap(AccountInfo accountInfo, ObjectInfo cloudFile, FileInfo fileInfo, string url, TreeHash treeHash, CancellationToken token)
\r
264 if (accountInfo == null)
\r
265 throw new ArgumentNullException("accountInfo");
\r
266 if (cloudFile == null)
\r
267 throw new ArgumentNullException("cloudFile");
\r
268 if (fileInfo == null)
\r
269 throw new ArgumentNullException("fileInfo");
\r
270 if (String.IsNullOrWhiteSpace(url))
\r
271 throw new ArgumentNullException(url);
\r
272 if (treeHash == null)
\r
273 throw new ArgumentNullException("treeHash");
\r
274 if (String.IsNullOrWhiteSpace(cloudFile.Container))
\r
275 throw new ArgumentException("Invalid container", "cloudFile");
\r
276 Contract.EndContractBlock();
\r
279 using (StatusNotification.GetNotifier("Uploading {0}", "Finished Uploading {0}", fileInfo.Name))
\r
281 if (await WaitOrAbort(accountInfo,cloudFile, token))
\r
284 var fullFileName = fileInfo.GetProperCapitalization();
\r
286 var account = cloudFile.Account ?? accountInfo.UserName;
\r
287 var container = cloudFile.Container;
\r
290 var client = new CloudFilesClient(accountInfo);
\r
291 //Send the hashmap to the server
\r
292 var missingHashes = await client.PutHashMap(account, container, url, treeHash);
\r
294 ReportUploadProgress(fileInfo.Name, block++, missingHashes.Count, fileInfo.Length);
\r
295 //If the server returns no missing hashes, we are done
\r
296 while (missingHashes.Count > 0)
\r
299 if (await WaitOrAbort(accountInfo,cloudFile, token))
\r
303 var buffer = new byte[accountInfo.BlockSize];
\r
304 foreach (var missingHash in missingHashes)
\r
306 if (await WaitOrAbort(accountInfo,cloudFile, token))
\r
310 //Find the proper block
\r
311 var blockIndex = treeHash.HashDictionary[missingHash];
\r
312 long offset = blockIndex*accountInfo.BlockSize;
\r
314 var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
\r
318 //And upload the block
\r
319 await client.PostBlock(account, container, buffer, 0, read, token);
\r
320 Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
\r
322 catch (TaskCanceledException exc)
\r
324 throw new OperationCanceledException(token);
\r
326 catch (Exception exc)
\r
328 Log.Error(String.Format("Uploading block {0} of {1}", blockIndex, fullFileName), exc);
\r
330 ReportUploadProgress(fileInfo.Name, block++, missingHashes.Count, fileInfo.Length);
\r
333 token.ThrowIfCancellationRequested();
\r
334 //Repeat until there are no more missing hashes
\r
335 missingHashes = await client.PutHashMap(account, container, url, treeHash);
\r
338 ReportUploadProgress(fileInfo.Name, missingHashes.Count, missingHashes.Count, fileInfo.Length);
\r
342 private async Task<bool> WaitOrAbort(AccountInfo account,ObjectInfo cloudFile, CancellationToken token)
\r
344 token.ThrowIfCancellationRequested();
\r
345 await UnpauseEvent.WaitAsync();
\r
346 var shouldAbort = !Selectives.IsSelected(account,cloudFile);
\r
348 Log.InfoFormat("Aborting [{0}]",cloudFile.Uri);
\r
349 return shouldAbort;
\r
352 private void ReportUploadProgress(string fileName, int block, int totalBlocks, long fileSize)
\r
354 StatusNotification.Notify(totalBlocks == 0
\r
355 ? new ProgressNotification(fileName, "Uploading", 1, 1, fileSize)
\r
356 : new ProgressNotification(fileName, "Uploading", block, totalBlocks, fileSize));
\r
360 private bool HandleUploadWebException(CloudAction action, WebException exc)
\r
362 var response = exc.Response as HttpWebResponse;
\r
363 if (response == null)
\r
365 if (response.StatusCode == HttpStatusCode.Unauthorized)
\r
367 Log.Error("Not allowed to upload file", exc);
\r
368 var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
\r
369 StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal, "");
\r
370 StatusNotification.NotifyChange(message, TraceLevel.Warning);
\r
377 public Selectives Selectives { get; set; }
\r
379 public AsyncManualResetEvent UnpauseEvent { get; set; }
\r