Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 7e26c075

History | View | Annotate | Download (41.7 kB)

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

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

    
23
        [Import]
24
        public IStatusKeeper StatusKeeper { get; set; }
25
        
26
        public IStatusNotification StatusNotification { get; set; }
27
/*
28
        [Import]
29
        public FileAgent FileAgent {get;set;}
30
*/
31

    
32
       /* public int BlockSize { get; set; }
33
        public string BlockHash { get; set; }*/
34

    
35
        private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
36

    
37
        private List<AccountInfo> _accounts=new List<AccountInfo>();
38

    
39
        public void Start(/*int blockSize, string blockHash*/)
40
        {
41
/*
42
            if (blockSize<0)
43
                throw new ArgumentOutOfRangeException("blockSize");
44
            if (String.IsNullOrWhiteSpace(blockHash))
45
                throw new ArgumentOutOfRangeException("blockHash");
46
            Contract.EndContractBlock();
47
*/
48

    
49
/*
50
            BlockSize = blockSize;
51
            BlockHash = blockHash;
52
*/
53

    
54

    
55
            _agent = Agent<CloudAction>.Start(inbox =>
56
            {
57
                Action loop = null;
58
                loop = () =>
59
                {
60
                    var message = inbox.Receive();
61
                    var process=message.Then(Process,inbox.CancellationToken);
62
                    inbox.LoopAsync(process, loop);
63
                };
64
                loop();
65
            });
66
        }
67

    
68
        private Task<object> Process(CloudAction action)
69
        {
70
            if (action == null)
71
                throw new ArgumentNullException("action");
72
            if (action.AccountInfo==null)
73
                throw new ArgumentException("The action.AccountInfo is empty","action");
74
            Contract.EndContractBlock();
75

    
76
            var accountInfo = action.AccountInfo;
77

    
78
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
79
            {                
80
                Log.InfoFormat("[ACTION] Start Processing {0}:{1}->{2}", action.Action, action.LocalFile,
81
                               action.CloudFile.Name);
82

    
83
                var localFile = action.LocalFile;
84
                var cloudFile = action.CloudFile;
85
                var downloadPath = action.GetDownloadPath();
86

    
87
                try
88
                {
89

    
90
                    switch (action.Action)
91
                    {
92
                        case CloudActionType.UploadUnconditional:
93
                            UploadCloudFile(action);
94
                            break;
95
                        case CloudActionType.DownloadUnconditional:
96

    
97
                            DownloadCloudFile(accountInfo,  cloudFile,downloadPath);
98
                            break;
99
                        case CloudActionType.DeleteCloud:
100
                            DeleteCloudFile(accountInfo, cloudFile, cloudFile.Name);
101
                            break;
102
                        case CloudActionType.RenameCloud:
103
                            var moveAction = (CloudMoveAction)action;
104
                            RenameCloudFile(accountInfo, cloudFile, moveAction);
105
                            break;
106
                        case CloudActionType.MustSynch:
107

    
108
                            if (!File.Exists(downloadPath))
109
                            {                                
110
                                DownloadCloudFile(accountInfo, cloudFile, downloadPath);
111
                            }
112
                            else
113
                            {
114
                                SyncFiles(accountInfo, action);
115
                            }
116
                            break;
117
                    }
118
                    Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
119
                                           action.CloudFile.Name);
120
                }
121
                catch (OperationCanceledException)
122
                {
123
                    throw;
124
                }
125
                catch (FileNotFoundException exc)
126
                {
127
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
128
                        action.Action, action.LocalFile, action.CloudFile, exc);
129
                    //Post a delete action for the missing file
130
                    Post(new CloudDeleteAction(action));
131
                }
132
                catch (Exception exc)
133
                {
134
                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
135
                                     action.Action, action.LocalFile, action.CloudFile, exc);
136

    
137
                    _agent.Post(action);
138
                }
139
                return CompletedTask<object>.Default;
140
            }
141
        }
142

    
143
        private void SyncFiles(AccountInfo accountInfo,CloudAction action)
144
        {
145
            if (accountInfo == null)
146
                throw new ArgumentNullException("accountInfo");
147
            if (action==null)
148
                throw new ArgumentNullException("action");
149
            if (action.LocalFile==null)
150
                throw new ArgumentException("The action's local file is not specified","action");
151
            if (!Path.IsPathRooted(action.LocalFile.FullName))
152
                throw new ArgumentException("The action's local file path must be absolute","action");
153
            if (action.CloudFile== null)
154
                throw new ArgumentException("The action's cloud file is not specified", "action");
155
            Contract.EndContractBlock();
156

    
157
            var localFile = action.LocalFile;
158
            var cloudFile = action.CloudFile;
159
            var downloadPath=action.LocalFile.FullName.ToLower();
160

    
161
            var cloudHash = cloudFile.Hash.ToLower();
162
            var localHash = action.LocalHash.Value.ToLower();
163
            var topHash = action.TopHash.Value.ToLower();
164

    
165
            //Not enough to compare only the local hashes, also have to compare the tophashes
166
            
167
            //If any of the hashes match, we are done
168
            if ((cloudHash == localHash || cloudHash == topHash))
169
            {
170
                Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
171
                return;
172
            }
173

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

    
203
                        //In both cases we must mark the file as in conflict
204
                        ReportConflict(downloadPath);
205
                        break;
206
                    default:
207
                        //Other cases should never occur. Mark them as Conflict as well but log a warning
208
                        ReportConflict(downloadPath);
209
                        Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
210
                                       downloadPath, action.CloudFile.Name);
211
                        break;
212
                }
213
            }
214
        }
215

    
216
        private void ReportConflict(string downloadPath)
217
        {
218
            if (String.IsNullOrWhiteSpace(downloadPath))
219
                throw new ArgumentNullException("downloadPath");
220
            Contract.EndContractBlock();
221

    
222
            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
223
            var message = String.Format("Conflict detected for file {0}", downloadPath);
224
            Log.Warn(message);
225
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
226
        }
227

    
228
        public void Post(CloudAction cloudAction)
229
        {
230
            if (cloudAction == null)
231
                throw new ArgumentNullException("cloudAction");
232
            if (cloudAction.AccountInfo==null)
233
                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
234
            Contract.EndContractBlock();
235
            
236
            //If the action targets a local file, add a treehash calculation
237
            if (cloudAction.LocalFile != null)
238
            {
239
                var accountInfo = cloudAction.AccountInfo;
240
                if (cloudAction.LocalFile.Length>accountInfo.BlockSize)
241
                    cloudAction.TopHash = new Lazy<string>(() => Signature.CalculateTreeHashAsync(cloudAction.LocalFile,
242
                                    accountInfo.BlockSize, accountInfo.BlockHash).Result
243
                                     .TopHash.ToHashString());
244
                else
245
                {
246
                    cloudAction.TopHash=new Lazy<string>(()=> cloudAction.LocalHash.Value);
247
                }
248

    
249
            }
250
            _agent.Post(cloudAction);
251
        }
252

    
253
        class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
254
        {
255
            public bool Equals(ObjectInfo x, ObjectInfo y)
256
            {
257
                return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
258
            }
259

    
260
            public int GetHashCode(ObjectInfo obj)
261
            {
262
                return obj.Name.ToLower().GetHashCode();
263
            }
264
        }
265

    
266
        
267

    
268
        //Remote files are polled periodically. Any changes are processed
269
        public Task ProcessRemoteFiles(DateTime? since=null)
270
        {
271
            return Task<Task>.Factory.StartNewDelayed(10000, () =>
272
            {
273
                using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
274
                {
275
                    //Next time we will check for all changes since the current check minus 1 second
276
                    //This is done to ensure there are no discrepancies due to clock differences
277
                    DateTime nextSince = DateTime.Now.AddSeconds(-1);
278
                    
279
                    var tasks=from accountInfo in _accounts
280
                              select ProcessAccountFiles(accountInfo, since);
281
                    var process=Task.Factory.Iterate(tasks);
282

    
283
                    return process.ContinueWith(t =>
284
                    {
285
                        if (t.IsFaulted)
286
                        {
287
                            Log.Error("Error while processing accounts");
288
                            t.Exception.Handle(exc=>
289
                                                   {
290
                                                       Log.Error("Details:", exc);
291
                                                       return true;
292
                                                   });                            
293
                        }
294
                        ProcessRemoteFiles(nextSince);
295
                    });
296
                }
297
            });            
298
        }
299

    
300
        public Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
301
        {   
302
            if (accountInfo==null)
303
                throw new ArgumentNullException("accountInfo");
304
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
305
                throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
306
            Contract.EndContractBlock();
307

    
308
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
309
            {
310
                Log.Info("Scheduled");
311
                var client=new CloudFilesClient(accountInfo);
312

    
313
                //Get the list of server objects changed since the last check
314
                var listObjects = Task<IList<ObjectInfo>>.Factory.StartNew(() =>
315
                                client.ListObjects(accountInfo.UserName, FolderConstants.PithosContainer, since));
316
                //Get the list of deleted objects since the last check
317
                var listTrash = Task<IList<ObjectInfo>>.Factory.StartNew(() =>
318
                                client.ListObjects(accountInfo.UserName, FolderConstants.TrashContainer, since));
319

    
320
                var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(() =>
321
                                client.ListSharedObjects(since));
322

    
323
                var listAll = Task.Factory.TrackedSequence(
324
                    () => listObjects,
325
                    () => listTrash,
326
                    () => listShared);
327

    
328

    
329

    
330
                var enqueueFiles = listAll.ContinueWith(task =>
331
                {
332
                    if (task.IsFaulted)
333
                    {
334
                        //ListObjects failed at this point, need to reschedule
335
                        Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {0}", accountInfo.UserName,task.Exception);
336
                        return;
337
                    }
338
                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
339
                    {
340
                        var remoteObjects = ((Task<IList<ObjectInfo>>) task.Result[0]).Result;
341
                        var trashObjects = ((Task<IList<ObjectInfo>>) task.Result[1]).Result;
342
                        var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
343

    
344
                        //Items with the same name, hash may be both in the container and the trash
345
                        //Don't delete items that exist in the container
346
                        var realTrash = from trash in trashObjects
347
                                        where !remoteObjects.Any(info => info.Hash == trash.Hash)
348
                                        select trash;
349
                        ProcessDeletedFiles(accountInfo,realTrash);                        
350

    
351

    
352
                        var remote = from info in remoteObjects.Union(sharedObjects)
353
                                     let name = info.Name
354
                                     where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
355
                                           !name.StartsWith("fragments/", StringComparison.InvariantCultureIgnoreCase)
356
                                     select info;
357

    
358
                        //Create a list of actions from the remote files
359
                        var allActions = ObjectsToActions(accountInfo,remote);
360
                       
361
                        //And remove those that are already being processed by the agent
362
                        var distinctActions = allActions
363
                            .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
364
                            .ToList();
365

    
366
                        //Queue all the actions
367
                        foreach (var message in distinctActions)
368
                        {
369
                            Post(message);
370
                        }
371

    
372
                        //Report the number of new files
373
                        var remoteCount = distinctActions.Count(action=>
374
                            action.Action==CloudActionType.DownloadUnconditional);
375
/*
376
                        if ( remoteCount > 0)
377
                            StatusNotification.NotifyChange(String.Format("Processing {0} new files", remoteCount));
378
*/
379

    
380
                        Log.Info("[LISTENER] End Processing");                        
381
                    }
382
                });
383

    
384
                var log = enqueueFiles.ContinueWith(t =>
385
                {                    
386
                    if (t.IsFaulted)
387
                    {
388
                        Log.Error("[LISTENER] Exception", t.Exception);
389
                    }
390
                    else
391
                    {
392
                        Log.Info("[LISTENER] Finished");
393
                    }
394
                });
395
                return log;
396
            }
397
        }
398

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

    
407
            //In order to avoid multiple iterations over the files, we iterate only once
408
            //over the remote files
409
            foreach (var objectInfo in remote)
410
            {
411
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
412
                //and remove any matching objects from the list, adding them to the commonObjects list
413
                
414
                if (fileAgent.Exists(relativePath))
415
                {
416
                    var localFile = fileAgent.GetFileInfo(relativePath);
417
                    var state = FileState.FindByFilePath(localFile.FullName);
418
                    //Common files should be checked on a per-case basis to detect differences, which is newer
419

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

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

    
444
        private void ProcessDeletedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
445
        {
446
            var fileAgent = GetFileAgent(accountInfo);
447
            foreach (var trashObject in trashObjects)
448
            {
449
                var relativePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
450
                //and remove any matching objects from the list, adding them to the commonObjects list
451
                fileAgent.Delete(relativePath);                                
452
            }
453
        }
454

    
455

    
456
        private void RenameCloudFile(AccountInfo accountInfo,ObjectInfo cloudFile,CloudMoveAction action)
457
        {
458
            if (accountInfo==null)
459
                throw new ArgumentNullException("accountInfo");
460
            if (cloudFile==null)
461
                throw new ArgumentNullException("cloudFile");
462
            if (action==null)
463
                throw new ArgumentNullException("action");
464
            Contract.EndContractBlock();
465
            //The local file is already renamed
466
            this.StatusKeeper.SetFileOverlayStatus(action.NewPath, FileOverlayStatus.Modified);
467

    
468

    
469
            var account = action.CloudFile.Account ?? accountInfo.UserName;
470
            var container = action.CloudFile.Container ?? FolderConstants.PithosContainer;
471
            
472
            var client = new CloudFilesClient(accountInfo);
473
            client.MoveObject(account, container, action.OldFileName, container, action.NewFileName);
474

    
475
            this.StatusKeeper.SetFileStatus(action.NewPath, FileStatus.Unchanged);
476
            this.StatusKeeper.SetFileOverlayStatus(action.NewPath, FileOverlayStatus.Normal);
477
            NativeMethods.RaiseChangeNotification(action.NewPath);
478
        }
479

    
480
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile,string fileName)
481
        {
482
            if (accountInfo == null)
483
                throw new ArgumentNullException("accountInfo");
484
            if (cloudFile==null)
485
                throw new ArgumentNullException("cloudFile");
486

    
487
            if (String.IsNullOrWhiteSpace(fileName))
488
                throw new ArgumentNullException("fileName");
489
            if (Path.IsPathRooted(fileName))
490
                throw new ArgumentException("The fileName should not be rooted","fileName");
491
            Contract.EndContractBlock();
492
            
493
            var fileAgent = GetFileAgent(accountInfo);
494

    
495
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
496
            {
497
                var info = fileAgent.GetFileInfo(fileName);
498
                var fullPath = info.FullName.ToLower();
499
                this.StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
500

    
501
                var account = cloudFile.Account ?? accountInfo.UserName;
502
                var container = cloudFile.Container ?? FolderConstants.PithosContainer;
503

    
504
                var client = new CloudFilesClient(accountInfo);
505
                client.DeleteObject(account, container, fileName);
506

    
507
                this.StatusKeeper.ClearFileStatus(fullPath);
508
            }
509
        }
510

    
511
        //Download a file.
512
        private void DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string localPath)
513
        {
514
            if (accountInfo == null)
515
                throw new ArgumentNullException("accountInfo");
516
            if (cloudFile == null)
517
                throw new ArgumentNullException("cloudFile");
518
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
519
                throw new ArgumentNullException("cloudFile");
520
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
521
                throw new ArgumentNullException("cloudFile");
522
            if (String.IsNullOrWhiteSpace(localPath))
523
                throw new ArgumentNullException("localPath");
524
            if (!Path.IsPathRooted(localPath))
525
                throw new ArgumentException("The localPath must be rooted", "localPath");
526
            Contract.EndContractBlock();
527
            
528
            var download=Task.Factory.Iterate(DownloadIterator(accountInfo,cloudFile, localPath));
529
            download.Wait();
530
        }
531

    
532
        private IEnumerable<Task> DownloadIterator(AccountInfo accountInfo,ObjectInfo cloudFile, string localPath)
533
        {
534
            if (accountInfo == null)
535
                throw new ArgumentNullException("accountInfo");
536
            if (cloudFile == null)
537
                throw new ArgumentNullException("cloudFile");
538
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
539
                throw new ArgumentNullException("cloudFile");
540
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
541
                throw new ArgumentNullException("cloudFile");
542
            if (String.IsNullOrWhiteSpace(localPath))
543
                throw new ArgumentNullException("localPath");
544
            if (!Path.IsPathRooted(localPath))
545
                throw new ArgumentException("The localPath must be rooted", "localPath");
546
            Contract.EndContractBlock();
547

    
548
            Uri relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
549

    
550
            var url = relativeUrl.ToString();
551
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
552
                yield break;
553

    
554
            //Are we already downloading or uploading the file? 
555
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
556
            {
557
                if (gate.Failed)
558
                    yield break;
559
                //The file's hashmap will be stored in the same location with the extension .hashmap
560
                //var hashPath = Path.Combine(FileAgent.FragmentsPath, relativePath + ".hashmap");
561
                
562
                var client = new CloudFilesClient(accountInfo);
563
                var account = cloudFile.Account;
564
                var container = cloudFile.Container;
565

    
566
                //Retrieve the hashmap from the server
567
                var getHashMap = client.GetHashMap(account, container, url);
568
                yield return getHashMap;
569
                
570
                var serverHash=getHashMap.Result;
571
                //If it's a small file
572
                var downloadTask=(serverHash.Hashes.Count == 1 )
573
                    //Download it in one go
574
                    ? DownloadEntireFile(accountInfo,client, cloudFile, relativeUrl, localPath, serverHash) 
575
                    //Otherwise download it block by block
576
                    : DownloadWithBlocks(accountInfo,client, cloudFile, relativeUrl, localPath, serverHash);
577

    
578
                yield return downloadTask;
579

    
580
                if (cloudFile.AllowedTo == "read")
581
                {
582
                    var attributes=File.GetAttributes(localPath);
583
                    File.SetAttributes(localPath,attributes|FileAttributes.ReadOnly);
584
                }
585
                
586
                //Now we can store the object's metadata without worrying about ghost status entries
587
                StatusKeeper.StoreInfo(localPath, cloudFile);
588
                
589
            }
590
        }
591

    
592
        //Download a small file with a single GET operation
593
        private Task DownloadEntireFile(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string localPath,TreeHash serverHash)
594
        {
595
            if (client == null)
596
                throw new ArgumentNullException("client");
597
            if (cloudFile==null)
598
                throw new ArgumentNullException("cloudFile");
599
            if (relativeUrl == null)
600
                throw new ArgumentNullException("relativeUrl");
601
            if (String.IsNullOrWhiteSpace(localPath))
602
                throw new ArgumentNullException("localPath");
603
            if (!Path.IsPathRooted(localPath))
604
                throw new ArgumentException("The localPath must be rooted", "localPath");
605
            Contract.EndContractBlock();
606

    
607
            //If the file already exists
608
            if (File.Exists(localPath))
609
            {
610
                //First check with MD5 as this is a small file
611
                var localMD5 = Signature.CalculateMD5(localPath);
612
                var cloudHash=serverHash.TopHash.ToHashString();
613
                if (localMD5==cloudHash)
614
                    return CompletedTask.Default;
615
                //Then check with a treehash
616
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
617
                var localHash = localTreeHash.TopHash.ToHashString();
618
                if (localHash==cloudHash)
619
                    return CompletedTask.Default;
620
            }
621

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

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

    
648
            });
649
            return getObject;
650
        }
651

    
652
        //Download a file asynchronously using blocks
653
        public Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string localPath, TreeHash serverHash)
654
        {
655
            if (client == null)
656
                throw new ArgumentNullException("client");
657
            if (cloudFile == null)
658
                throw new ArgumentNullException("cloudFile");
659
            if (relativeUrl == null)
660
                throw new ArgumentNullException("relativeUrl");
661
            if (String.IsNullOrWhiteSpace(localPath))
662
                throw new ArgumentNullException("localPath");
663
            if (!Path.IsPathRooted(localPath))
664
                throw new ArgumentException("The localPath must be rooted", "localPath");
665
            if (serverHash == null)
666
                throw new ArgumentNullException("serverHash");
667
            Contract.EndContractBlock();
668
            
669
            return Task.Factory.Iterate(BlockDownloadIterator(accountInfo,client,cloudFile, relativeUrl, localPath, serverHash));
670
        }
671

    
672
        private IEnumerable<Task> BlockDownloadIterator(AccountInfo accountInfo,CloudFilesClient client,  ObjectInfo cloudFile, Uri relativeUrl, string localPath, TreeHash serverHash)
673
        {
674
            if (client == null)
675
                throw new ArgumentNullException("client");
676
            if (cloudFile==null)
677
                throw new ArgumentNullException("cloudFile");
678
            if (relativeUrl == null)
679
                throw new ArgumentNullException("relativeUrl");
680
            if (String.IsNullOrWhiteSpace(localPath))
681
                throw new ArgumentNullException("localPath");
682
            if (!Path.IsPathRooted(localPath))
683
                throw new ArgumentException("The localPath must be rooted", "localPath");
684
            if(serverHash==null)
685
                throw new ArgumentNullException("serverHash");
686
            Contract.EndContractBlock();
687
            
688
            var fileAgent = GetFileAgent(accountInfo);
689
            
690
            //Calculate the relative file path for the new file
691
            var relativePath = relativeUrl.RelativeUriToFilePath();
692
            var blockUpdater = new BlockUpdater(fileAgent.FragmentsPath, localPath, relativePath, serverHash);
693

    
694
            
695
                        
696
            //Calculate the file's treehash
697
            var calcHash = Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize,serverHash.BlockHash);
698
            yield return calcHash;                        
699
            var treeHash = calcHash.Result;
700
                
701
            //And compare it with the server's hash
702
            var upHashes = serverHash.GetHashesAsStrings();
703
            var localHashes = treeHash.HashDictionary;
704
            for (int i = 0; i < upHashes.Length; i++)
705
            {
706
                //For every non-matching hash
707
                var upHash = upHashes[i];
708
                if (!localHashes.ContainsKey(upHash))
709
                {
710
                    if (blockUpdater.UseOrphan(i, upHash))
711
                    {
712
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
713
                        continue;
714
                    }
715
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
716
                    var start = i*serverHash.BlockSize;
717
                    //To download the last block just pass a null for the end of the range
718
                    long? end = null;
719
                    if (i < upHashes.Length - 1 )
720
                        end= ((i + 1)*serverHash.BlockSize) ;
721
                            
722
                    //Download the missing block
723
                    var getBlock = client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
724
                    yield return getBlock;
725
                    var block = getBlock.Result;
726

    
727
                    //and store it
728
                    yield return blockUpdater.StoreBlock(i, block);
729

    
730

    
731
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
732
                }
733
            }
734

    
735
            //Want to avoid notifications if no changes were made
736
            var hasChanges = blockUpdater.HasBlocks;
737
            blockUpdater.Commit();
738
            
739
            if (hasChanges)
740
                //Notify listeners that a local file has changed
741
                StatusNotification.NotifyChangedFile(localPath);
742

    
743
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
744
        }
745

    
746

    
747
        private void UploadCloudFile(CloudAction action)
748
        {
749
            if (action == null)
750
                throw new ArgumentNullException("action");           
751
            Contract.EndContractBlock();
752

    
753
            try
754
            {
755
                var upload = Task.Factory.Iterate(UploadIterator(action));
756
                upload.Wait();
757
            }                
758
            catch (AggregateException ex)
759
            {                
760
                var exc = ex.InnerException as WebException;
761
                if (exc==null)
762
                    throw ex.InnerException;
763
                var response = exc.Response as HttpWebResponse;
764
                if (response==null)
765
                    throw exc;
766
                if (response.StatusCode == HttpStatusCode.Unauthorized)
767
                {
768
                    Log.Error("Not allowed to upload file", exc);
769
                    var message = String.Format("Not allowed to uplad file {0}",action.LocalFile.FullName);
770
                    StatusKeeper.SetFileState(action.LocalFile.FullName,FileStatus.Unchanged,FileOverlayStatus.Normal);
771
                    StatusNotification.NotifyChange(message,TraceLevel.Warning);
772
                    return;
773
                }
774
                throw;
775
            }
776
        }
777

    
778
        private IEnumerable<Task> UploadIterator(CloudAction action)
779
        {
780
            if (action == null)
781
                throw new ArgumentNullException("action");            
782
            Contract.EndContractBlock();
783

    
784
            var accountInfo=action.AccountInfo;
785
            
786
            var fileInfo=action.LocalFile;                        
787

    
788
            if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
789
                yield break;
790

    
791
            var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
792
            if (relativePath.StartsWith(FolderConstants.OthersFolder))
793
            {
794
                var parts=relativePath.Split('\\');
795
                var accountName = parts[1];
796
                var oldName = accountInfo.UserName;
797
                   var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
798
                var nameIndex=absoluteUri.IndexOf(oldName);
799
                var root=absoluteUri.Substring(0, nameIndex);
800

    
801
                accountInfo = new AccountInfo
802
                {
803
                    UserName = accountName,
804
                    AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
805
                    StorageUri = new Uri(root + accountName),
806
                    BlockHash=accountInfo.BlockHash,
807
                    BlockSize=accountInfo.BlockSize,
808
                    Token=accountInfo.Token
809
                };
810
            }
811

    
812

    
813
            var url = fileInfo.AsRelativeUrlTo(accountInfo.AccountPath);
814

    
815
            
816

    
817
            var fullFileName = fileInfo.FullName;
818
            using(var gate=NetworkGate.Acquire(fullFileName,NetworkOperation.Uploading))
819
            {
820
                //Abort if the file is already being uploaded or downloaded
821
                if (gate.Failed)
822
                    yield break;
823

    
824
                var cloudFile = action.CloudFile;
825
                var account = cloudFile.Account ?? accountInfo.UserName;
826
                var container = cloudFile.Container ?? FolderConstants.PithosContainer;
827

    
828
                var client = new CloudFilesClient(accountInfo);
829
                //Even if GetObjectInfo times out, we can proceed with the upload            
830
                var info = client.GetObjectInfo(account, container, url);                
831
                var cloudHash = info.Hash.ToLower();
832

    
833
                var hash = action.LocalHash.Value;
834
                var topHash = action.TopHash.Value;
835

    
836
                //If the file hashes match, abort the upload
837
                if (hash == cloudHash  || topHash ==cloudHash)
838
                {
839
                    //but store any metadata changes 
840
                    this.StatusKeeper.StoreInfo(fullFileName, info);
841
                    Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
842
                    yield break;
843
                }
844

    
845
                if (info.AllowedTo=="read")
846
                    yield break;
847

    
848
                //Mark the file as modified while we upload it
849
                StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
850
                //And then upload it
851

    
852
                //If the file is larger than the block size, try a hashmap PUT
853
                if (fileInfo.Length > accountInfo.BlockSize )
854
                {
855
                    //To upload using a hashmap
856
                    //First, calculate the tree hash
857
                    var treeHash = Signature.CalculateTreeHashAsync(fileInfo.FullName, accountInfo.BlockSize,
858
                        accountInfo.BlockHash);
859
                    yield return treeHash;
860
                    
861
                    yield return Task.Factory.Iterate(UploadWithHashMap(accountInfo,cloudFile,fileInfo,url,treeHash));
862
                                        
863
                }
864
                else
865
                {
866
                    //Otherwise do a regular PUT
867
                    yield return client.PutObject(account, container, url, fullFileName, hash);                    
868
                }
869
                //If everything succeeds, change the file and overlay status to normal
870
                this.StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
871
            }
872
            //Notify the Shell to update the overlays
873
            NativeMethods.RaiseChangeNotification(fullFileName);
874
            StatusNotification.NotifyChangedFile(fullFileName);
875
        }
876

    
877
        public IEnumerable<Task> UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,Task<TreeHash> treeHash)
878
        {
879
            if (accountInfo == null)
880
                throw new ArgumentNullException("accountInfo");
881
            if (cloudFile==null)
882
                throw new ArgumentNullException("cloudFile");
883
            if (fileInfo == null)
884
                throw new ArgumentNullException("fileInfo");
885
            if (String.IsNullOrWhiteSpace(url))
886
                throw new ArgumentNullException(url);
887
            if (treeHash==null)
888
                throw new ArgumentNullException("treeHash");
889
            Contract.EndContractBlock();
890

    
891
            var fullFileName = fileInfo.FullName;
892

    
893
            var account = cloudFile.Account ?? accountInfo.UserName;
894
            var container = cloudFile.Container ?? FolderConstants.PithosContainer;
895

    
896
            var client = new CloudFilesClient(accountInfo);
897
            //Send the hashmap to the server            
898
            var hashPut = client.PutHashMap(account, container, url, treeHash.Result);
899
            yield return hashPut;
900

    
901
            var missingHashes = hashPut.Result;
902
            //If the server returns no missing hashes, we are done
903
            while (missingHashes.Count > 0)
904
            {
905

    
906
                var buffer = new byte[accountInfo.BlockSize];
907
                foreach (var missingHash in missingHashes)
908
                {
909
                    //Find the proper block
910
                    var blockIndex = treeHash.Result.HashDictionary[missingHash];
911
                    var offset = blockIndex*accountInfo.BlockSize;
912

    
913
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
914

    
915
                    //And upload the block                
916
                    var postBlock = client.PostBlock(account, container, buffer, 0, read);
917

    
918
                    //We have to handle possible exceptions in a continuation because
919
                    //*yield return* can't appear inside a try block
920
                    yield return postBlock.ContinueWith(t => 
921
                        t.ReportExceptions(
922
                            exc => Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc),
923
                            ()=>Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex,fullFileName)));
924
                }
925

    
926
                //Repeat until there are no more missing hashes
927
                hashPut = client.PutHashMap(account, container, url, treeHash.Result);
928
                yield return hashPut;
929
                missingHashes = hashPut.Result;
930
            }
931
        }
932

    
933

    
934
        public void AddAccount(AccountInfo accountInfo)
935
        {            
936
            if (!_accounts.Contains(accountInfo))
937
                _accounts.Add(accountInfo);
938
        }
939
    }
940

    
941
   
942

    
943

    
944
}