Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 73cdd135

History | View | Annotate | Download (39.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.Threading.Tasks;
10
using Pithos.Interfaces;
11
using Pithos.Network;
12
using log4net;
13

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

    
21

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

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

    
29
        private readonly List<AccountInfo> _accounts=new List<AccountInfo>();
30

    
31
        public void Start()
32
        {
33

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

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

    
55
            var accountInfo = action.AccountInfo;
56

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

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

    
64
                try
65
                {
66

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

    
74
                            await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
75
                            break;
76
                        case CloudActionType.DeleteCloud:
77
                            DeleteCloudFile(accountInfo, cloudFile);
78
                            break;
79
                        case CloudActionType.RenameCloud:
80
                            var moveAction = (CloudMoveAction)action;
81
                            RenameCloudFile(accountInfo, moveAction);
82
                            break;
83
                        case CloudActionType.MustSynch:
84

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

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

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

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

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

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

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

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

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

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

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

    
241
            }
242
            _agent.Post(cloudAction);
243
        }
244

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

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

    
258
        
259

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

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

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

    
274
                    var tasks = from accountInfo in _accounts
275
                                select ProcessAccountFiles(accountInfo, since);
276

    
277
                    await TaskEx.WhenAll(tasks);
278

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

    
289
            }
290
        }
291

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

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

    
305
                var containers = client.ListContainers(accountInfo.UserName);
306
                
307
                CreateContainerFolders(accountInfo, containers);
308

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

    
318

    
319
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
320

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

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

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

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

    
343

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

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

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

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

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

    
375
                Log.Info("[LISTENER] Finished");
376

    
377
            }
378
        }
379

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

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

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

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

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

    
433
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
434
        {
435
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
436
        }
437

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

    
451

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

    
472

    
473
            var account = action.CloudFile.Account ?? accountInfo.UserName;
474
            var container = action.CloudFile.Container;
475
            
476
            var client = new CloudFilesClient(accountInfo);
477
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
478

    
479
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
480
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
481
            NativeMethods.RaiseChangeNotification(newFilePath);
482
        }
483

    
484
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
485
        {
486
            if (accountInfo == null)
487
                throw new ArgumentNullException("accountInfo");
488
            if (cloudFile==null)
489
                throw new ArgumentNullException("cloudFile");
490

    
491
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
492
                throw new ArgumentException("Invalid container", "cloudFile");
493
            Contract.EndContractBlock();
494
            
495
            var fileAgent = GetFileAgent(accountInfo);
496

    
497
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
498
            {
499
                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
500
                var info = fileAgent.GetFileInfo(fileName);                
501
                var fullPath = info.FullName.ToLower();
502

    
503
                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
504

    
505
                var account = cloudFile.Account ?? accountInfo.UserName;
506
                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
507

    
508
                var client = new CloudFilesClient(accountInfo);
509
                client.DeleteObject(account, container, cloudFile.Name);
510

    
511
                StatusKeeper.ClearFileStatus(fullPath);
512
            }
513
        }
514

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

    
534
            var url = relativeUrl.ToString();
535
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
536
                return;
537

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

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

    
568
                    if (cloudFile.AllowedTo == "read")
569
                    {
570
                        var attributes = File.GetAttributes(localPath);
571
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
572
                    }
573
                }
574

    
575
                //Now we can store the object's metadata without worrying about ghost status entries
576
                StatusKeeper.StoreInfo(localPath, cloudFile);
577
                
578
            }
579
        }
580

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

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

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

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

    
637
            });            
638
        }
639

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

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

    
692
                    //and store it
693
                    blockUpdater.StoreBlock(i, block);
694

    
695

    
696
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
697
                }
698
            }
699

    
700
            //Want to avoid notifications if no changes were made
701
            var hasChanges = blockUpdater.HasBlocks;
702
            blockUpdater.Commit();
703
            
704
            if (hasChanges)
705
                //Notify listeners that a local file has changed
706
                StatusNotification.NotifyChangedFile(localPath);
707

    
708
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
709
        }
710

    
711

    
712
        private async Task UploadCloudFile(CloudAction action)
713
        {
714
            if (action == null)
715
                throw new ArgumentNullException("action");           
716
            Contract.EndContractBlock();
717

    
718
            try
719
            {
720
                var accountInfo = action.AccountInfo;
721

    
722
                var fileInfo = action.LocalFile;
723

    
724
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
725
                    return;
726

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

    
737
                    accountInfo = new AccountInfo
738
                    {
739
                        UserName = accountName,
740
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
741
                        StorageUri = new Uri(root + accountName),
742
                        BlockHash = accountInfo.BlockHash,
743
                        BlockSize = accountInfo.BlockSize,
744
                        Token = accountInfo.Token
745
                    };
746
                }
747

    
748

    
749
                var fullFileName = fileInfo.FullName;
750
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
751
                {
752
                    //Abort if the file is already being uploaded or downloaded
753
                    if (gate.Failed)
754
                        return;
755

    
756
                    var cloudFile = action.CloudFile;
757
                    var account = cloudFile.Account ?? accountInfo.UserName;
758

    
759
                    var client = new CloudFilesClient(accountInfo);
760
                    //Even if GetObjectInfo times out, we can proceed with the upload            
761
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
762
                    var cloudHash = info.Hash.ToLower();
763

    
764
                    var hash = action.LocalHash.Value;
765
                    var topHash = action.TopHash.Value;
766

    
767
                    //If the file hashes match, abort the upload
768
                    if (hash == cloudHash || topHash == cloudHash)
769
                    {
770
                        //but store any metadata changes 
771
                        StatusKeeper.StoreInfo(fullFileName, info);
772
                        Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
773
                        return;
774
                    }
775

    
776
                    if (info.AllowedTo == "read")
777
                        return;
778

    
779
                    //Mark the file as modified while we upload it
780
                    StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
781
                    //And then upload it
782

    
783
                    //Upload even small files using the Hashmap. The server may already containt
784
                    //the relevant folder
785

    
786
                    //First, calculate the tree hash
787
                    var treeHash = await Signature.CalculateTreeHashAsync(fileInfo.FullName, accountInfo.BlockSize,
788
                        accountInfo.BlockHash);
789

    
790
                    await UploadWithHashMap(accountInfo, cloudFile, fileInfo, cloudFile.Name, treeHash);
791

    
792
                    //If everything succeeds, change the file and overlay status to normal
793
                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
794
                }
795
                //Notify the Shell to update the overlays
796
                NativeMethods.RaiseChangeNotification(fullFileName);
797
                StatusNotification.NotifyChangedFile(fullFileName);
798
            }
799
            catch (AggregateException ex)
800
            {
801
                var exc = ex.InnerException as WebException;
802
                if (exc == null)
803
                    throw ex.InnerException;
804
                if (HandleUploadWebException(action, exc)) 
805
                    return;
806
                throw;
807
            }
808
            catch (WebException ex)
809
            {
810
                if (HandleUploadWebException(action, ex))
811
                    return;
812
                throw;
813
            }
814
            catch (Exception ex)
815
            {
816
                Log.Error("Unexpected error while uploading file", ex);
817
                throw;
818
            }
819

    
820
        }
821

    
822
        private bool HandleUploadWebException(CloudAction action, WebException exc)
823
        {
824
            var response = exc.Response as HttpWebResponse;
825
            if (response == null)
826
                throw exc;
827
            if (response.StatusCode == HttpStatusCode.Unauthorized)
828
            {
829
                Log.Error("Not allowed to upload file", exc);
830
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
831
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
832
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
833
                return true;
834
            }
835
            return false;
836
        }
837

    
838
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
839
        {
840
            if (accountInfo == null)
841
                throw new ArgumentNullException("accountInfo");
842
            if (cloudFile==null)
843
                throw new ArgumentNullException("cloudFile");
844
            if (fileInfo == null)
845
                throw new ArgumentNullException("fileInfo");
846
            if (String.IsNullOrWhiteSpace(url))
847
                throw new ArgumentNullException(url);
848
            if (treeHash==null)
849
                throw new ArgumentNullException("treeHash");
850
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
851
                throw new ArgumentException("Invalid container","cloudFile");
852
            Contract.EndContractBlock();
853

    
854
            var fullFileName = fileInfo.FullName;
855

    
856
            var account = cloudFile.Account ?? accountInfo.UserName;
857
            var container = cloudFile.Container ;
858

    
859
            var client = new CloudFilesClient(accountInfo);
860
            //Send the hashmap to the server            
861
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
862
            //If the server returns no missing hashes, we are done
863
            while (missingHashes.Count > 0)
864
            {
865

    
866
                var buffer = new byte[accountInfo.BlockSize];
867
                foreach (var missingHash in missingHashes)
868
                {
869
                    //Find the proper block
870
                    var blockIndex = treeHash.HashDictionary[missingHash];
871
                    var offset = blockIndex*accountInfo.BlockSize;
872

    
873
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
874

    
875
                    try
876
                    {
877
                        //And upload the block                
878
                        await client.PostBlock(account, container, buffer, 0, read);
879
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
880
                    }
881
                    catch (Exception exc)
882
                    {
883
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
884
                    }
885

    
886
                }
887

    
888
                //Repeat until there are no more missing hashes                
889
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
890
            }
891
        }
892

    
893

    
894
        public void AddAccount(AccountInfo accountInfo)
895
        {            
896
            if (!_accounts.Contains(accountInfo))
897
                _accounts.Add(accountInfo);
898
        }
899
    }
900

    
901
   
902

    
903

    
904
}