Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 0bd56b7c

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
                        if ( remoteCount > 0)
376
                            StatusNotification.NotifyChange(String.Format("Processing {0} new files", remoteCount));
377

    
378
                        Log.Info("[LISTENER] End Processing");                        
379
                    }
380
                });
381

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

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

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

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

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

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

    
453

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

    
466

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

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

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

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

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

    
499
                var account = cloudFile.Account ?? accountInfo.UserName;
500
                var container = cloudFile.Container ?? FolderConstants.PithosContainer;
501

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

    
505
                this.StatusKeeper.ClearFileStatus(fullPath);
506
            }
507
        }
508

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

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

    
546
            Uri relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
547

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

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

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

    
576
                yield return downloadTask;
577

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

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

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

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

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

    
646
            });
647
            return getObject;
648
        }
649

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

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

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

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

    
728

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

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

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

    
744

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

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

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

    
782
            var accountInfo=action.AccountInfo;
783
            
784
            var fileInfo=action.LocalFile;                        
785

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

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

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

    
810

    
811
            var url = fileInfo.AsRelativeUrlTo(accountInfo.AccountPath);
812

    
813
            
814

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

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

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

    
831
                var hash = action.LocalHash.Value;
832
                var topHash = action.TopHash.Value;
833

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

    
843
                if (info.AllowedTo=="read")
844
                    yield break;
845

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

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

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

    
889
            var fullFileName = fileInfo.FullName;
890

    
891
            var account = cloudFile.Account ?? accountInfo.UserName;
892
            var container = cloudFile.Container ?? FolderConstants.PithosContainer;
893

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

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

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

    
911
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
912

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

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

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

    
931

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

    
939
   
940

    
941

    
942
}