Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 4f6d51d4

History | View | Annotate | Download (41.1 kB)

1
using System;
2
using System.Collections.Concurrent;
3
using System.Collections.Generic;
4
using System.ComponentModel.Composition;
5
using System.Diagnostics;
6
using System.Diagnostics.Contracts;
7
using System.IO;
8
using System.Linq;
9
using System.Net;
10
using System.Threading.Tasks;
11
using Pithos.Interfaces;
12
using Pithos.Network;
13
using log4net;
14

    
15
namespace Pithos.Core.Agents
16
{
17
    [Export]
18
    public class NetworkAgent
19
    {
20
        private Agent<CloudAction> _agent;
21

    
22

    
23
        [Import]
24
        public IStatusKeeper StatusKeeper { get; set; }
25
        
26
        public IStatusNotification StatusNotification { get; set; }
27

    
28
        private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
29

    
30
        private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
31

    
32
        public void Start()
33
        {
34

    
35
            _agent = Agent<CloudAction>.Start(inbox =>
36
            {
37
                Action loop = null;
38
                loop = () =>
39
                {
40
                    var message = inbox.Receive();
41
                    var process=message.Then(Process,inbox.CancellationToken);
42
                    inbox.LoopAsync(process, loop);
43
                };
44
                loop();
45
            });           
46
        }
47

    
48
        private async Task Process(CloudAction action)
49
        {
50
            if (action == null)
51
                throw new ArgumentNullException("action");
52
            if (action.AccountInfo==null)
53
                throw new ArgumentException("The action.AccountInfo is empty","action");
54
            Contract.EndContractBlock();
55

    
56
            var accountInfo = action.AccountInfo;
57

    
58
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
59
            {                
60
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
61

    
62
                var cloudFile = action.CloudFile;
63
                var downloadPath = action.GetDownloadPath();
64

    
65
                try
66
                {
67

    
68
                    switch (action.Action)
69
                    {
70
                        case CloudActionType.UploadUnconditional:
71
                            await UploadCloudFile(action);
72
                            break;
73
                        case CloudActionType.DownloadUnconditional:
74

    
75
                            await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
76
                            break;
77
                        case CloudActionType.DeleteCloud:
78
                            DeleteCloudFile(accountInfo, cloudFile);
79
                            break;
80
                        case CloudActionType.RenameCloud:
81
                            var moveAction = (CloudMoveAction)action;
82
                            RenameCloudFile(accountInfo, moveAction);
83
                            break;
84
                        case CloudActionType.MustSynch:
85
                            if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
86
                            {
87
                                await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
88
                            }
89
                            else
90
                            {
91
                                await SyncFiles(accountInfo, action);
92
                            }
93
                            break;
94
                    }
95
                    Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
96
                                           action.CloudFile.Name);
97
                }
98
                catch (WebException exc)
99
                {
100
                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
101
                }
102
                catch (OperationCanceledException)
103
                {
104
                    throw;
105
                }
106
                catch (DirectoryNotFoundException)
107
                {
108
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
109
                        action.Action, action.LocalFile, action.CloudFile);
110
                    //Post a delete action for the missing file
111
                    Post(new CloudDeleteAction(action));                    
112
                }
113
                catch (FileNotFoundException)
114
                {
115
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
116
                        action.Action, action.LocalFile, action.CloudFile);
117
                    //Post a delete action for the missing file
118
                    Post(new CloudDeleteAction(action));
119
                }
120
                catch (Exception exc)
121
                {
122
                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
123
                                     action.Action, action.LocalFile, action.CloudFile, exc);
124

    
125
                    _agent.Post(action);
126
                }                
127
            }
128
        }
129

    
130
        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
131
        {
132
            if (accountInfo == null)
133
                throw new ArgumentNullException("accountInfo");
134
            if (action==null)
135
                throw new ArgumentNullException("action");
136
            if (action.LocalFile==null)
137
                throw new ArgumentException("The action's local file is not specified","action");
138
            if (!Path.IsPathRooted(action.LocalFile.FullName))
139
                throw new ArgumentException("The action's local file path must be absolute","action");
140
            if (action.CloudFile== null)
141
                throw new ArgumentException("The action's cloud file is not specified", "action");
142
            Contract.EndContractBlock();
143

    
144
            var localFile = action.LocalFile;
145
            var cloudFile = action.CloudFile;
146
            var downloadPath=action.LocalFile.FullName.ToLower();
147

    
148
            var cloudHash = cloudFile.Hash.ToLower();
149
            var localHash = action.LocalHash.Value.ToLower();
150
            var topHash = action.TopHash.Value.ToLower();
151

    
152
            //Not enough to compare only the local hashes, also have to compare the tophashes
153
            
154
            //If any of the hashes match, we are done
155
            if ((cloudHash == localHash || cloudHash == topHash))
156
            {
157
                Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
158
                return;
159
            }
160

    
161
            //The hashes DON'T match. We need to sync
162
            var lastLocalTime = localFile.LastWriteTime;
163
            var lastUpTime = cloudFile.Last_Modified;
164
            
165
            //If the local file is newer upload it
166
            if (lastUpTime <= lastLocalTime)
167
            {
168
                //It probably means it was changed while the app was down                        
169
                UploadCloudFile(action);
170
            }
171
            else
172
            {
173
                //It the cloud file has a later date, it was modified by another user or computer.
174
                //We need to check the local file's status                
175
                var status = StatusKeeper.GetFileStatus(downloadPath);
176
                switch (status)
177
                {
178
                    case FileStatus.Unchanged:                        
179
                        //If the local file's status is Unchanged, we can go on and download the newer cloud file
180
                        await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
181
                        break;
182
                    case FileStatus.Modified:
183
                        //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
184
                        //We can't ensure that a file modified online since the last time will appear as Modified, unless we 
185
                        //index all files before we start listening.                       
186
                    case FileStatus.Created:
187
                        //If the local file is Created, it means that the local and cloud files aren't related,
188
                        // yet they have the same name.
189

    
190
                        //In both cases we must mark the file as in conflict
191
                        ReportConflict(downloadPath);
192
                        break;
193
                    default:
194
                        //Other cases should never occur. Mark them as Conflict as well but log a warning
195
                        ReportConflict(downloadPath);
196
                        Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
197
                                       downloadPath, action.CloudFile.Name);
198
                        break;
199
                }
200
            }
201
        }
202

    
203
        private void ReportConflict(string downloadPath)
204
        {
205
            if (String.IsNullOrWhiteSpace(downloadPath))
206
                throw new ArgumentNullException("downloadPath");
207
            Contract.EndContractBlock();
208

    
209
            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
210
            var message = String.Format("Conflict detected for file {0}", downloadPath);
211
            Log.Warn(message);
212
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
213
        }
214

    
215
        public void Post(CloudAction cloudAction)
216
        {
217
            if (cloudAction == null)
218
                throw new ArgumentNullException("cloudAction");
219
            if (cloudAction.AccountInfo==null)
220
                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
221
            Contract.EndContractBlock();
222
            
223
            //If the action targets a local file, add a treehash calculation
224
            if (cloudAction.LocalFile as FileInfo != null)
225
            {
226
                var accountInfo = cloudAction.AccountInfo;
227
                var localFile = (FileInfo) cloudAction.LocalFile;
228
                if (localFile.Length > accountInfo.BlockSize)
229
                    cloudAction.TopHash =
230
                        new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
231
                                                                                accountInfo.BlockSize,
232
                                                                                accountInfo.BlockHash).Result
233
                                                    .TopHash.ToHashString());
234
                else
235
                {
236
                    cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
237
                }
238
            }
239
            else
240
            {
241
                //The hash for a directory is the empty string
242
                cloudAction.TopHash = new Lazy<string>(() => String.Empty);
243
            }
244
            _agent.Post(cloudAction);
245
        }
246

    
247
       /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
248
        {
249
            public bool Equals(ObjectInfo x, ObjectInfo y)
250
            {
251
                return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
252
            }
253

    
254
            public int GetHashCode(ObjectInfo obj)
255
            {
256
                return obj.Name.ToLower().GetHashCode();
257
            }
258
        }*/
259

    
260
        
261

    
262
        //Remote files are polled periodically. Any changes are processed
263
        public async Task ProcessRemoteFiles(DateTime? since = null)
264
        {            
265
            await TaskEx.Delay(TimeSpan.FromSeconds(10),_agent.CancellationToken);
266

    
267
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
268
            {
269

    
270
                try
271
                {
272
                    //Next time we will check for all changes since the current check minus 1 second
273
                    //This is done to ensure there are no discrepancies due to clock differences
274
                    DateTime nextSince = DateTime.Now.AddSeconds(-1);
275

    
276
                    var tasks = from accountInfo in _accounts
277
                                select ProcessAccountFiles(accountInfo, since);
278

    
279
                    await TaskEx.WhenAll(tasks.ToList());
280

    
281
                    ProcessRemoteFiles(nextSince);
282
                }
283
                catch (Exception ex)
284
                {
285
                    Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
286
                    //In case of failure retry with the same parameter
287
                    ProcessRemoteFiles(since);
288
                }
289
                
290

    
291
            }
292
        }
293

    
294
        public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
295
        {   
296
            if (accountInfo==null)
297
                throw new ArgumentNullException("accountInfo");
298
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
299
                throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
300
            Contract.EndContractBlock();
301

    
302
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
303
            {
304
                Log.Info("Scheduled");
305
                var client=new CloudFilesClient(accountInfo);
306

    
307
                var containers = client.ListContainers(accountInfo.UserName);
308
                
309
                CreateContainerFolders(accountInfo, containers);
310

    
311
                try
312
                {
313
                    
314
                    //Get the list of server objects changed since the last check
315
                    //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
316
                    var listObjects = from container in containers
317
                                      select  Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
318
                                            client.ListObjects(accountInfo.UserName,container.Name, since),container.Name);
319

    
320

    
321
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
322

    
323
                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
324
                    {
325
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
326

    
327
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
328
                        var remoteObjects = from objectList in listTasks
329
                                            where (string) objectList.AsyncState != "trash"
330
                                            from obj in objectList.Result
331
                                            select obj;
332

    
333
                        var trashObjects = dict["trash"].Result;
334
                        //var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
335

    
336
                        //Items with the same name, hash may be both in the container and the trash
337
                        //Don't delete items that exist in the container
338
                        var realTrash = from trash in trashObjects
339
                                        where
340
                                            !remoteObjects.Any(
341
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
342
                                        select trash;
343
                        ProcessDeletedFiles(accountInfo, realTrash);
344

    
345

    
346
                        var remote = from info in remoteObjects
347
                                     //.Union(sharedObjects)
348
                                     let name = info.Name
349
                                     where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
350
                                           !name.StartsWith(FolderConstants.CacheFolder + "/",
351
                                                            StringComparison.InvariantCultureIgnoreCase)
352
                                     select info;
353

    
354
                        //Create a list of actions from the remote files
355
                        var allActions = ObjectsToActions(accountInfo, remote);
356

    
357
                        //And remove those that are already being processed by the agent
358
                        var distinctActions = allActions
359
                            .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
360
                            .ToList();
361

    
362
                        //Queue all the actions
363
                        foreach (var message in distinctActions)
364
                        {
365
                            Post(message);
366
                        }
367

    
368
                        Log.Info("[LISTENER] End Processing");
369
                    }
370
                }
371
                catch (Exception ex)
372
                {
373
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
374
                    return;
375
                }
376

    
377
                Log.Info("[LISTENER] Finished");
378

    
379
            }
380
        }
381

    
382
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
383
        {
384
            var containerPaths = from container in containers
385
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
386
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
387
                                 select containerPath;
388

    
389
            foreach (var path in containerPaths)
390
            {
391
                Directory.CreateDirectory(path);
392
            }
393
        }
394

    
395
        //Creates an appropriate action for each server file
396
        private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
397
        {
398
            if (remote==null)
399
                throw new ArgumentNullException();
400
            Contract.EndContractBlock();
401
            var fileAgent = GetFileAgent(accountInfo);
402

    
403
            //In order to avoid multiple iterations over the files, we iterate only once
404
            //over the remote files
405
            foreach (var objectInfo in remote)
406
            {
407
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
408
                //and remove any matching objects from the list, adding them to the commonObjects list
409
                
410
                if (fileAgent.Exists(relativePath))
411
                {
412
                    //If a directory object already exists, we don't need to perform any other action                    
413
                    var localFile = fileAgent.GetFileInfo(relativePath);
414
                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
415
                        continue;
416
                    var state = FileState.FindByFilePath(localFile.FullName);
417
                    //Common files should be checked on a per-case basis to detect differences, which is newer
418

    
419
                    yield return new CloudAction(accountInfo,CloudActionType.MustSynch,
420
                                                   localFile, objectInfo, state, accountInfo.BlockSize,
421
                                                   accountInfo.BlockHash);
422
                }
423
                else
424
                {
425
                    //If there is no match we add them to the localFiles list
426
                    //but only if the file is not marked for deletion
427
                    var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
428
                    var fileStatus = StatusKeeper.GetFileStatus(targetFile);
429
                    if (fileStatus != FileStatus.Deleted)
430
                    {
431
                        //Remote files should be downloaded
432
                        yield return new CloudDownloadAction(accountInfo,objectInfo);
433
                    }
434
                }
435
            }            
436
        }
437

    
438
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
439
        {
440
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
441
        }
442

    
443
        private void ProcessDeletedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
444
        {
445
            var fileAgent = GetFileAgent(accountInfo);
446
            foreach (var trashObject in trashObjects)
447
            {
448
                var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
449
                //HACK: Assume only the "pithos" container is used. Must find out what happens when
450
                //deleting a file from a different container
451
                var relativePath = Path.Combine("pithos", barePath);
452
                fileAgent.Delete(relativePath);                                
453
            }
454
        }
455

    
456

    
457
        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
458
        {
459
            if (accountInfo==null)
460
                throw new ArgumentNullException("accountInfo");
461
            if (action==null)
462
                throw new ArgumentNullException("action");
463
            if (action.CloudFile==null)
464
                throw new ArgumentException("CloudFile","action");
465
            if (action.LocalFile==null)
466
                throw new ArgumentException("LocalFile","action");
467
            if (action.OldLocalFile==null)
468
                throw new ArgumentException("OldLocalFile","action");
469
            if (action.OldCloudFile==null)
470
                throw new ArgumentException("OldCloudFile","action");
471
            Contract.EndContractBlock();
472
            
473
            var newFilePath = action.LocalFile.FullName;            
474
            //The local file is already renamed
475
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
476

    
477

    
478
            var account = action.CloudFile.Account ?? accountInfo.UserName;
479
            var container = action.CloudFile.Container;
480
            
481
            var client = new CloudFilesClient(accountInfo);
482
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
483

    
484
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
485
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
486
            NativeMethods.RaiseChangeNotification(newFilePath);
487
        }
488

    
489
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
490
        {
491
            if (accountInfo == null)
492
                throw new ArgumentNullException("accountInfo");
493
            if (cloudFile==null)
494
                throw new ArgumentNullException("cloudFile");
495

    
496
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
497
                throw new ArgumentException("Invalid container", "cloudFile");
498
            Contract.EndContractBlock();
499
            
500
            var fileAgent = GetFileAgent(accountInfo);
501

    
502
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
503
            {
504
                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
505
                var info = fileAgent.GetFileInfo(fileName);                
506
                var fullPath = info.FullName.ToLower();
507

    
508
                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
509

    
510
                var account = cloudFile.Account ?? accountInfo.UserName;
511
                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
512

    
513
                var client = new CloudFilesClient(accountInfo);
514
                client.DeleteObject(account, container, cloudFile.Name);
515

    
516
                StatusKeeper.ClearFileStatus(fullPath);
517
            }
518
        }
519

    
520
        //Download a file.
521
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string localPath)
522
        {
523
            if (accountInfo == null)
524
                throw new ArgumentNullException("accountInfo");
525
            if (cloudFile == null)
526
                throw new ArgumentNullException("cloudFile");
527
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
528
                throw new ArgumentNullException("cloudFile");
529
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
530
                throw new ArgumentNullException("cloudFile");
531
            if (String.IsNullOrWhiteSpace(localPath))
532
                throw new ArgumentNullException("localPath");
533
            if (!Path.IsPathRooted(localPath))
534
                throw new ArgumentException("The localPath must be rooted", "localPath");
535
            Contract.EndContractBlock();
536
                       
537
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
538

    
539
            var url = relativeUrl.ToString();
540
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
541
                return;
542

    
543
            //Are we already downloading or uploading the file? 
544
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
545
            {
546
                if (gate.Failed)
547
                    return;
548
                //The file's hashmap will be stored in the same location with the extension .hashmap
549
                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
550
                
551
                var client = new CloudFilesClient(accountInfo);
552
                var account = cloudFile.Account;
553
                var container = cloudFile.Container;
554

    
555
                if (cloudFile.Content_Type == @"application/directory")
556
                {
557
                    if (!Directory.Exists(localPath))
558
                        Directory.CreateDirectory(localPath);
559
                }
560
                else
561
                {
562
                    //Retrieve the hashmap from the server
563
                    var serverHash = await client.GetHashMap(account, container, url);
564
                    //If it's a small file
565
                    if (serverHash.Hashes.Count == 1)
566
                        //Download it in one go
567
                        await
568
                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
569
                        //Otherwise download it block by block
570
                    else
571
                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
572

    
573
                    if (cloudFile.AllowedTo == "read")
574
                    {
575
                        var attributes = File.GetAttributes(localPath);
576
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
577
                    }
578
                }
579

    
580
                //Now we can store the object's metadata without worrying about ghost status entries
581
                StatusKeeper.StoreInfo(localPath, cloudFile);
582
                
583
            }
584
        }
585

    
586
        //Download a small file with a single GET operation
587
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string localPath,TreeHash serverHash)
588
        {
589
            if (client == null)
590
                throw new ArgumentNullException("client");
591
            if (cloudFile==null)
592
                throw new ArgumentNullException("cloudFile");
593
            if (relativeUrl == null)
594
                throw new ArgumentNullException("relativeUrl");
595
            if (String.IsNullOrWhiteSpace(localPath))
596
                throw new ArgumentNullException("localPath");
597
            if (!Path.IsPathRooted(localPath))
598
                throw new ArgumentException("The localPath must be rooted", "localPath");
599
            Contract.EndContractBlock();
600

    
601
            //If the file already exists
602
            if (File.Exists(localPath))
603
            {
604
                //First check with MD5 as this is a small file
605
                var localMD5 = Signature.CalculateMD5(localPath);
606
                var cloudHash=serverHash.TopHash.ToHashString();
607
                if (localMD5==cloudHash)
608
                    return;
609
                //Then check with a treehash
610
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
611
                var localHash = localTreeHash.TopHash.ToHashString();
612
                if (localHash==cloudHash)
613
                    return;
614
            }
615

    
616
            var fileAgent = GetFileAgent(accountInfo);
617
            //Calculate the relative file path for the new file
618
            var relativePath = relativeUrl.RelativeUriToFilePath();
619
            //The file will be stored in a temporary location while downloading with an extension .download
620
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
621
            //Make sure the target folder exists. DownloadFileTask will not create the folder
622
            var tempFolder = Path.GetDirectoryName(tempPath);
623
            if (!Directory.Exists(tempFolder))
624
                Directory.CreateDirectory(tempFolder);
625

    
626
            //Download the object to the temporary location
627
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath).ContinueWith(t =>
628
            {
629
                t.PropagateExceptions();
630
                //Create the local folder if it doesn't exist (necessary for shared objects)
631
                var localFolder = Path.GetDirectoryName(localPath);
632
                if (!Directory.Exists(localFolder))
633
                    Directory.CreateDirectory(localFolder);
634
                //And move it to its actual location once downloading is finished
635
                if (File.Exists(localPath))
636
                    File.Replace(tempPath,localPath,null,true);
637
                else
638
                    File.Move(tempPath,localPath);
639
                //Notify listeners that a local file has changed
640
                StatusNotification.NotifyChangedFile(localPath);
641

    
642
            });            
643
        }
644

    
645
        //Download a file asynchronously using blocks
646
        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string localPath, TreeHash serverHash)
647
        {
648
            if (client == null)
649
                throw new ArgumentNullException("client");
650
            if (cloudFile == null)
651
                throw new ArgumentNullException("cloudFile");
652
            if (relativeUrl == null)
653
                throw new ArgumentNullException("relativeUrl");
654
            if (String.IsNullOrWhiteSpace(localPath))
655
                throw new ArgumentNullException("localPath");
656
            if (!Path.IsPathRooted(localPath))
657
                throw new ArgumentException("The localPath must be rooted", "localPath");
658
            if (serverHash == null)
659
                throw new ArgumentNullException("serverHash");
660
            Contract.EndContractBlock();
661
            
662
           var fileAgent = GetFileAgent(accountInfo);
663
            
664
            //Calculate the relative file path for the new file
665
            var relativePath = relativeUrl.RelativeUriToFilePath();
666
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
667

    
668
            
669
                        
670
            //Calculate the file's treehash
671
            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
672
                
673
            //And compare it with the server's hash
674
            var upHashes = serverHash.GetHashesAsStrings();
675
            var localHashes = treeHash.HashDictionary;
676
            for (int i = 0; i < upHashes.Length; i++)
677
            {
678
                //For every non-matching hash
679
                var upHash = upHashes[i];
680
                if (!localHashes.ContainsKey(upHash))
681
                {
682
                    if (blockUpdater.UseOrphan(i, upHash))
683
                    {
684
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
685
                        continue;
686
                    }
687
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
688
                    var start = i*serverHash.BlockSize;
689
                    //To download the last block just pass a null for the end of the range
690
                    long? end = null;
691
                    if (i < upHashes.Length - 1 )
692
                        end= ((i + 1)*serverHash.BlockSize) ;
693
                            
694
                    //Download the missing block
695
                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
696

    
697
                    //and store it
698
                    blockUpdater.StoreBlock(i, block);
699

    
700

    
701
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
702
                }
703
            }
704

    
705
            //Want to avoid notifications if no changes were made
706
            var hasChanges = blockUpdater.HasBlocks;
707
            blockUpdater.Commit();
708
            
709
            if (hasChanges)
710
                //Notify listeners that a local file has changed
711
                StatusNotification.NotifyChangedFile(localPath);
712

    
713
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
714
        }
715

    
716

    
717
        private async Task UploadCloudFile(CloudAction action)
718
        {
719
            if (action == null)
720
                throw new ArgumentNullException("action");           
721
            Contract.EndContractBlock();
722

    
723
            try
724
            {
725
                var accountInfo = action.AccountInfo;
726

    
727
                var fileInfo = action.LocalFile;
728

    
729
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
730
                    return;
731

    
732
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
733
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
734
                {
735
                    var parts = relativePath.Split('\\');
736
                    var accountName = parts[1];
737
                    var oldName = accountInfo.UserName;
738
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
739
                    var nameIndex = absoluteUri.IndexOf(oldName);
740
                    var root = absoluteUri.Substring(0, nameIndex);
741

    
742
                    accountInfo = new AccountInfo
743
                    {
744
                        UserName = accountName,
745
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
746
                        StorageUri = new Uri(root + accountName),
747
                        BlockHash = accountInfo.BlockHash,
748
                        BlockSize = accountInfo.BlockSize,
749
                        Token = accountInfo.Token
750
                    };
751
                }
752

    
753

    
754
                var fullFileName = fileInfo.FullName;
755
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
756
                {
757
                    //Abort if the file is already being uploaded or downloaded
758
                    if (gate.Failed)
759
                        return;
760

    
761
                    var cloudFile = action.CloudFile;
762
                    var account = cloudFile.Account ?? accountInfo.UserName;
763

    
764
                    var client = new CloudFilesClient(accountInfo);                    
765
                    //Even if GetObjectInfo times out, we can proceed with the upload            
766
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
767

    
768
                    //If this is a read-only file, do not upload changes
769
                    if (info.AllowedTo == "read")
770
                        return;
771

    
772
                    //WRONG: If this is a directory, there is no hash to check. ????
773
                    //TODO: Check how a directory hash is calculated
774
                    if (fileInfo is DirectoryInfo)
775
                    {
776
                        //If the directory doesn't exist the Hash property will be empty
777
                        if (String.IsNullOrWhiteSpace(info.Hash))
778
                            //Go on and create the directory
779
                            client.PutObject(account, cloudFile.Container, cloudFile.Name, fileInfo.FullName, String.Empty, "application/directory");
780
                    }
781
                    else
782
                    {
783

    
784
                        var cloudHash = info.Hash.ToLower();
785

    
786
                        var hash = action.LocalHash.Value;
787
                        var topHash = action.TopHash.Value;
788

    
789
                        //If the file hashes match, abort the upload
790
                        if (hash == cloudHash || topHash == cloudHash)
791
                        {
792
                            //but store any metadata changes 
793
                            StatusKeeper.StoreInfo(fullFileName, info);
794
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
795
                            return;
796
                        }
797

    
798

    
799
                        //Mark the file as modified while we upload it
800
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
801
                        //And then upload it
802

    
803
                        //Upload even small files using the Hashmap. The server may already contain
804
                        //the relevant block
805

    
806
                        //First, calculate the tree hash
807
                        var treeHash = await Signature.CalculateTreeHashAsync(fileInfo.FullName, accountInfo.BlockSize,
808
                                                                              accountInfo.BlockHash);
809

    
810
                        await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
811
                    }
812
                    //If everything succeeds, change the file and overlay status to normal
813
                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
814
                }
815
                //Notify the Shell to update the overlays
816
                NativeMethods.RaiseChangeNotification(fullFileName);
817
                StatusNotification.NotifyChangedFile(fullFileName);
818
            }
819
            catch (AggregateException ex)
820
            {
821
                var exc = ex.InnerException as WebException;
822
                if (exc == null)
823
                    throw ex.InnerException;
824
                if (HandleUploadWebException(action, exc)) 
825
                    return;
826
                throw;
827
            }
828
            catch (WebException ex)
829
            {
830
                if (HandleUploadWebException(action, ex))
831
                    return;
832
                throw;
833
            }
834
            catch (Exception ex)
835
            {
836
                Log.Error("Unexpected error while uploading file", ex);
837
                throw;
838
            }
839

    
840
        }
841

    
842
        private bool HandleUploadWebException(CloudAction action, WebException exc)
843
        {
844
            var response = exc.Response as HttpWebResponse;
845
            if (response == null)
846
                throw exc;
847
            if (response.StatusCode == HttpStatusCode.Unauthorized)
848
            {
849
                Log.Error("Not allowed to upload file", exc);
850
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
851
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
852
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
853
                return true;
854
            }
855
            return false;
856
        }
857

    
858
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
859
        {
860
            if (accountInfo == null)
861
                throw new ArgumentNullException("accountInfo");
862
            if (cloudFile==null)
863
                throw new ArgumentNullException("cloudFile");
864
            if (fileInfo == null)
865
                throw new ArgumentNullException("fileInfo");
866
            if (String.IsNullOrWhiteSpace(url))
867
                throw new ArgumentNullException(url);
868
            if (treeHash==null)
869
                throw new ArgumentNullException("treeHash");
870
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
871
                throw new ArgumentException("Invalid container","cloudFile");
872
            Contract.EndContractBlock();
873

    
874
            var fullFileName = fileInfo.FullName;
875

    
876
            var account = cloudFile.Account ?? accountInfo.UserName;
877
            var container = cloudFile.Container ;
878

    
879
            var client = new CloudFilesClient(accountInfo);
880
            //Send the hashmap to the server            
881
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
882
            //If the server returns no missing hashes, we are done
883
            while (missingHashes.Count > 0)
884
            {
885

    
886
                var buffer = new byte[accountInfo.BlockSize];
887
                foreach (var missingHash in missingHashes)
888
                {
889
                    //Find the proper block
890
                    var blockIndex = treeHash.HashDictionary[missingHash];
891
                    var offset = blockIndex*accountInfo.BlockSize;
892

    
893
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
894

    
895
                    try
896
                    {
897
                        //And upload the block                
898
                        await client.PostBlock(account, container, buffer, 0, read);
899
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
900
                    }
901
                    catch (Exception exc)
902
                    {
903
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
904
                    }
905

    
906
                }
907

    
908
                //Repeat until there are no more missing hashes                
909
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
910
            }
911
        }
912

    
913

    
914
        public void AddAccount(AccountInfo accountInfo)
915
        {            
916
            if (!_accounts.Contains(accountInfo))
917
                _accounts.Add(accountInfo);
918
        }
919
    }
920

    
921
   
922

    
923

    
924
}