Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 5750d7cc

History | View | Annotate | Download (42.1 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
                var containers = client.ListContainers(accountInfo.UserName);
314
                
315
                CreateContainerFolders(accountInfo, containers);
316

    
317

    
318
                //Get the list of server objects changed since the last check
319
                var listObjects = Task<IList<ObjectInfo>>.Factory.StartNew(() =>
320
                                client.ListObjects(accountInfo.UserName, FolderConstants.PithosContainer, since));
321
                //Get the list of deleted objects since the last check
322
                var listTrash = Task<IList<ObjectInfo>>.Factory.StartNew(() =>
323
                                client.ListObjects(accountInfo.UserName, FolderConstants.TrashContainer, since));
324

    
325
                var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(() =>
326
                                client.ListSharedObjects(since));
327

    
328
                var listAll = Task.Factory.TrackedSequence(
329
                    () => listObjects,
330
                    () => listTrash,
331
                    () => listShared);
332

    
333

    
334

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

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

    
356

    
357
                        var remote = from info in remoteObjects.Union(sharedObjects)
358
                                     let name = info.Name
359
                                     where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
360
                                           !name.StartsWith(FolderConstants.CacheFolder +"/", StringComparison.InvariantCultureIgnoreCase)
361
                                     select info;
362

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

    
371
                        //Queue all the actions
372
                        foreach (var message in distinctActions)
373
                        {
374
                            Post(message);
375
                        }
376

    
377
                        //Report the number of new files
378
                        var remoteCount = distinctActions.Count(action=>
379
                            action.Action==CloudActionType.DownloadUnconditional);
380
/*
381
                        if ( remoteCount > 0)
382
                            StatusNotification.NotifyChange(String.Format("Processing {0} new files", remoteCount));
383
*/
384

    
385
                        Log.Info("[LISTENER] End Processing");                        
386
                    }
387
                });
388

    
389
                var log = enqueueFiles.ContinueWith(t =>
390
                {                    
391
                    if (t.IsFaulted)
392
                    {
393
                        Log.Error("[LISTENER] Exception", t.Exception);
394
                    }
395
                    else
396
                    {
397
                        Log.Info("[LISTENER] Finished");
398
                    }
399
                });
400
                return log;
401
            }
402
        }
403

    
404
        private static void CreateContainerFolders(AccountInfo accountInfo, IList<ContainerInfo> containers)
405
        {
406
            var containerPaths = from container in containers
407
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
408
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
409
                                 select containerPath;
410

    
411
            foreach (var path in containerPaths)
412
            {
413
                Directory.CreateDirectory(path);
414
            }
415
        }
416

    
417
        //Creates an appropriate action for each server file
418
        private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
419
        {
420
            if (remote==null)
421
                throw new ArgumentNullException();
422
            Contract.EndContractBlock();
423
            var fileAgent = GetFileAgent(accountInfo);
424

    
425
            //In order to avoid multiple iterations over the files, we iterate only once
426
            //over the remote files
427
            foreach (var objectInfo in remote)
428
            {
429
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
430
                //and remove any matching objects from the list, adding them to the commonObjects list
431
                
432
                if (fileAgent.Exists(relativePath))
433
                {
434
                    var localFile = fileAgent.GetFileInfo(relativePath);
435
                    var state = FileState.FindByFilePath(localFile.FullName);
436
                    //Common files should be checked on a per-case basis to detect differences, which is newer
437

    
438
                    yield return new CloudAction(accountInfo,CloudActionType.MustSynch,
439
                                                   localFile, objectInfo, state, accountInfo.BlockSize,
440
                                                   accountInfo.BlockHash);
441
                }
442
                else
443
                {
444
                    //If there is no match we add them to the localFiles list
445
                    //but only if the file is not marked for deletion
446
                    var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
447
                    var fileStatus = StatusKeeper.GetFileStatus(targetFile);
448
                    if (fileStatus != FileStatus.Deleted)
449
                    {
450
                        //Remote files should be downloaded
451
                        yield return new CloudDownloadAction(accountInfo,objectInfo);
452
                    }
453
                }
454
            }            
455
        }
456

    
457
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
458
        {
459
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
460
        }
461

    
462
        private void ProcessDeletedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
463
        {
464
            var fileAgent = GetFileAgent(accountInfo);
465
            foreach (var trashObject in trashObjects)
466
            {
467
                var relativePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
468
                //and remove any matching objects from the list, adding them to the commonObjects list
469
                fileAgent.Delete(relativePath);                                
470
            }
471
        }
472

    
473

    
474
        private void RenameCloudFile(AccountInfo accountInfo,ObjectInfo cloudFile,CloudMoveAction action)
475
        {
476
            if (accountInfo==null)
477
                throw new ArgumentNullException("accountInfo");
478
            if (cloudFile==null)
479
                throw new ArgumentNullException("cloudFile");
480
            if (action==null)
481
                throw new ArgumentNullException("action");
482
            Contract.EndContractBlock();
483
            //The local file is already renamed
484
            this.StatusKeeper.SetFileOverlayStatus(action.NewPath, FileOverlayStatus.Modified);
485

    
486

    
487
            var account = action.CloudFile.Account ?? accountInfo.UserName;
488
            var container = action.CloudFile.Container ?? FolderConstants.PithosContainer;
489
            
490
            var client = new CloudFilesClient(accountInfo);
491
            client.MoveObject(account, container, action.OldFileName, container, action.NewFileName);
492

    
493
            this.StatusKeeper.SetFileStatus(action.NewPath, FileStatus.Unchanged);
494
            this.StatusKeeper.SetFileOverlayStatus(action.NewPath, FileOverlayStatus.Normal);
495
            NativeMethods.RaiseChangeNotification(action.NewPath);
496
        }
497

    
498
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile,string fileName)
499
        {
500
            if (accountInfo == null)
501
                throw new ArgumentNullException("accountInfo");
502
            if (cloudFile==null)
503
                throw new ArgumentNullException("cloudFile");
504

    
505
            if (String.IsNullOrWhiteSpace(fileName))
506
                throw new ArgumentNullException("fileName");
507
            if (Path.IsPathRooted(fileName))
508
                throw new ArgumentException("The fileName should not be rooted","fileName");
509
            Contract.EndContractBlock();
510
            
511
            var fileAgent = GetFileAgent(accountInfo);
512

    
513
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
514
            {
515
                var info = fileAgent.GetFileInfo(fileName);
516
                var fullPath = info.FullName.ToLower();
517
                this.StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
518

    
519
                var account = cloudFile.Account ?? accountInfo.UserName;
520
                var container = cloudFile.Container ?? FolderConstants.PithosContainer;
521

    
522
                var client = new CloudFilesClient(accountInfo);
523
                client.DeleteObject(account, container, fileName);
524

    
525
                this.StatusKeeper.ClearFileStatus(fullPath);
526
            }
527
        }
528

    
529
        //Download a file.
530
        private void DownloadCloudFile(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
            var download=Task.Factory.Iterate(DownloadIterator(accountInfo,cloudFile, localPath));
547
            download.Wait();
548
        }
549

    
550
        private IEnumerable<Task> DownloadIterator(AccountInfo accountInfo,ObjectInfo cloudFile, string localPath)
551
        {
552
            if (accountInfo == null)
553
                throw new ArgumentNullException("accountInfo");
554
            if (cloudFile == null)
555
                throw new ArgumentNullException("cloudFile");
556
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
557
                throw new ArgumentNullException("cloudFile");
558
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
559
                throw new ArgumentNullException("cloudFile");
560
            if (String.IsNullOrWhiteSpace(localPath))
561
                throw new ArgumentNullException("localPath");
562
            if (!Path.IsPathRooted(localPath))
563
                throw new ArgumentException("The localPath must be rooted", "localPath");
564
            Contract.EndContractBlock();
565

    
566
            Uri relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
567

    
568
            var url = relativeUrl.ToString();
569
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
570
                yield break;
571

    
572
            //Are we already downloading or uploading the file? 
573
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
574
            {
575
                if (gate.Failed)
576
                    yield break;
577
                //The file's hashmap will be stored in the same location with the extension .hashmap
578
                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
579
                
580
                var client = new CloudFilesClient(accountInfo);
581
                var account = cloudFile.Account;
582
                var container = cloudFile.Container;
583

    
584
                //Retrieve the hashmap from the server
585
                var getHashMap = client.GetHashMap(account, container, url);
586
                yield return getHashMap;
587
                
588
                var serverHash=getHashMap.Result;
589
                //If it's a small file
590
                var downloadTask=(serverHash.Hashes.Count == 1 )
591
                    //Download it in one go
592
                    ? DownloadEntireFile(accountInfo,client, cloudFile, relativeUrl, localPath, serverHash) 
593
                    //Otherwise download it block by block
594
                    : DownloadWithBlocks(accountInfo,client, cloudFile, relativeUrl, localPath, serverHash);
595

    
596
                yield return downloadTask;
597

    
598
                if (cloudFile.AllowedTo == "read")
599
                {
600
                    var attributes=File.GetAttributes(localPath);
601
                    File.SetAttributes(localPath,attributes|FileAttributes.ReadOnly);
602
                }
603
                
604
                //Now we can store the object's metadata without worrying about ghost status entries
605
                StatusKeeper.StoreInfo(localPath, cloudFile);
606
                
607
            }
608
        }
609

    
610
        //Download a small file with a single GET operation
611
        private Task DownloadEntireFile(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string localPath,TreeHash serverHash)
612
        {
613
            if (client == null)
614
                throw new ArgumentNullException("client");
615
            if (cloudFile==null)
616
                throw new ArgumentNullException("cloudFile");
617
            if (relativeUrl == null)
618
                throw new ArgumentNullException("relativeUrl");
619
            if (String.IsNullOrWhiteSpace(localPath))
620
                throw new ArgumentNullException("localPath");
621
            if (!Path.IsPathRooted(localPath))
622
                throw new ArgumentException("The localPath must be rooted", "localPath");
623
            Contract.EndContractBlock();
624

    
625
            //If the file already exists
626
            if (File.Exists(localPath))
627
            {
628
                //First check with MD5 as this is a small file
629
                var localMD5 = Signature.CalculateMD5(localPath);
630
                var cloudHash=serverHash.TopHash.ToHashString();
631
                if (localMD5==cloudHash)
632
                    return CompletedTask.Default;
633
                //Then check with a treehash
634
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
635
                var localHash = localTreeHash.TopHash.ToHashString();
636
                if (localHash==cloudHash)
637
                    return CompletedTask.Default;
638
            }
639

    
640
            var fileAgent = GetFileAgent(accountInfo);
641
            //Calculate the relative file path for the new file
642
            var relativePath = relativeUrl.RelativeUriToFilePath();
643
            //The file will be stored in a temporary location while downloading with an extension .download
644
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
645
            //Make sure the target folder exists. DownloadFileTask will not create the folder
646
            var tempFolder = Path.GetDirectoryName(tempPath);
647
            if (!Directory.Exists(tempFolder))
648
                Directory.CreateDirectory(tempFolder);
649

    
650
            //Download the object to the temporary location
651
            var getObject = client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath).ContinueWith(t =>
652
            {
653
                t.PropagateExceptions();
654
                //Create the local folder if it doesn't exist (necessary for shared objects)
655
                var localFolder = Path.GetDirectoryName(localPath);
656
                if (!Directory.Exists(localFolder))
657
                    Directory.CreateDirectory(localFolder);
658
                //And move it to its actual location once downloading is finished
659
                if (File.Exists(localPath))
660
                    File.Replace(tempPath,localPath,null,true);
661
                else
662
                    File.Move(tempPath,localPath);
663
                //Notify listeners that a local file has changed
664
                StatusNotification.NotifyChangedFile(localPath);
665

    
666
            });
667
            return getObject;
668
        }
669

    
670
        //Download a file asynchronously using blocks
671
        public Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string localPath, TreeHash serverHash)
672
        {
673
            if (client == null)
674
                throw new ArgumentNullException("client");
675
            if (cloudFile == null)
676
                throw new ArgumentNullException("cloudFile");
677
            if (relativeUrl == null)
678
                throw new ArgumentNullException("relativeUrl");
679
            if (String.IsNullOrWhiteSpace(localPath))
680
                throw new ArgumentNullException("localPath");
681
            if (!Path.IsPathRooted(localPath))
682
                throw new ArgumentException("The localPath must be rooted", "localPath");
683
            if (serverHash == null)
684
                throw new ArgumentNullException("serverHash");
685
            Contract.EndContractBlock();
686
            
687
            return Task.Factory.Iterate(BlockDownloadIterator(accountInfo,client,cloudFile, relativeUrl, localPath, serverHash));
688
        }
689

    
690
        private IEnumerable<Task> BlockDownloadIterator(AccountInfo accountInfo,CloudFilesClient client,  ObjectInfo cloudFile, Uri relativeUrl, string localPath, TreeHash serverHash)
691
        {
692
            if (client == null)
693
                throw new ArgumentNullException("client");
694
            if (cloudFile==null)
695
                throw new ArgumentNullException("cloudFile");
696
            if (relativeUrl == null)
697
                throw new ArgumentNullException("relativeUrl");
698
            if (String.IsNullOrWhiteSpace(localPath))
699
                throw new ArgumentNullException("localPath");
700
            if (!Path.IsPathRooted(localPath))
701
                throw new ArgumentException("The localPath must be rooted", "localPath");
702
            if(serverHash==null)
703
                throw new ArgumentNullException("serverHash");
704
            Contract.EndContractBlock();
705
            
706
            var fileAgent = GetFileAgent(accountInfo);
707
            
708
            //Calculate the relative file path for the new file
709
            var relativePath = relativeUrl.RelativeUriToFilePath();
710
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
711

    
712
            
713
                        
714
            //Calculate the file's treehash
715
            var calcHash = Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize,serverHash.BlockHash);
716
            yield return calcHash;                        
717
            var treeHash = calcHash.Result;
718
                
719
            //And compare it with the server's hash
720
            var upHashes = serverHash.GetHashesAsStrings();
721
            var localHashes = treeHash.HashDictionary;
722
            for (int i = 0; i < upHashes.Length; i++)
723
            {
724
                //For every non-matching hash
725
                var upHash = upHashes[i];
726
                if (!localHashes.ContainsKey(upHash))
727
                {
728
                    if (blockUpdater.UseOrphan(i, upHash))
729
                    {
730
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
731
                        continue;
732
                    }
733
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
734
                    var start = i*serverHash.BlockSize;
735
                    //To download the last block just pass a null for the end of the range
736
                    long? end = null;
737
                    if (i < upHashes.Length - 1 )
738
                        end= ((i + 1)*serverHash.BlockSize) ;
739
                            
740
                    //Download the missing block
741
                    var getBlock = client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
742
                    yield return getBlock;
743
                    var block = getBlock.Result;
744

    
745
                    //and store it
746
                    yield return blockUpdater.StoreBlock(i, block);
747

    
748

    
749
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
750
                }
751
            }
752

    
753
            //Want to avoid notifications if no changes were made
754
            var hasChanges = blockUpdater.HasBlocks;
755
            blockUpdater.Commit();
756
            
757
            if (hasChanges)
758
                //Notify listeners that a local file has changed
759
                StatusNotification.NotifyChangedFile(localPath);
760

    
761
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
762
        }
763

    
764

    
765
        private void UploadCloudFile(CloudAction action)
766
        {
767
            if (action == null)
768
                throw new ArgumentNullException("action");           
769
            Contract.EndContractBlock();
770

    
771
            try
772
            {
773
                var upload = Task.Factory.Iterate(UploadIterator(action));
774
                upload.Wait();
775
            }                
776
            catch (AggregateException ex)
777
            {                
778
                var exc = ex.InnerException as WebException;
779
                if (exc==null)
780
                    throw ex.InnerException;
781
                var response = exc.Response as HttpWebResponse;
782
                if (response==null)
783
                    throw exc;
784
                if (response.StatusCode == HttpStatusCode.Unauthorized)
785
                {
786
                    Log.Error("Not allowed to upload file", exc);
787
                    var message = String.Format("Not allowed to uplad file {0}",action.LocalFile.FullName);
788
                    StatusKeeper.SetFileState(action.LocalFile.FullName,FileStatus.Unchanged,FileOverlayStatus.Normal);
789
                    StatusNotification.NotifyChange(message,TraceLevel.Warning);
790
                    return;
791
                }
792
                throw;
793
            }
794
        }
795

    
796
        private IEnumerable<Task> UploadIterator(CloudAction action)
797
        {
798
            if (action == null)
799
                throw new ArgumentNullException("action");            
800
            Contract.EndContractBlock();
801

    
802
            var accountInfo=action.AccountInfo;
803
            
804
            var fileInfo=action.LocalFile;                        
805

    
806
            if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
807
                yield break;
808

    
809
            var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
810
            if (relativePath.StartsWith(FolderConstants.OthersFolder))
811
            {
812
                var parts=relativePath.Split('\\');
813
                var accountName = parts[1];
814
                var oldName = accountInfo.UserName;
815
                   var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
816
                var nameIndex=absoluteUri.IndexOf(oldName);
817
                var root=absoluteUri.Substring(0, nameIndex);
818

    
819
                accountInfo = new AccountInfo
820
                {
821
                    UserName = accountName,
822
                    AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
823
                    StorageUri = new Uri(root + accountName),
824
                    BlockHash=accountInfo.BlockHash,
825
                    BlockSize=accountInfo.BlockSize,
826
                    Token=accountInfo.Token
827
                };
828
            }
829

    
830

    
831
            var url = fileInfo.AsRelativeUrlTo(accountInfo.AccountPath);
832

    
833
            
834

    
835
            var fullFileName = fileInfo.FullName;
836
            using(var gate=NetworkGate.Acquire(fullFileName,NetworkOperation.Uploading))
837
            {
838
                //Abort if the file is already being uploaded or downloaded
839
                if (gate.Failed)
840
                    yield break;
841

    
842
                var cloudFile = action.CloudFile;
843
                var account = cloudFile.Account ?? accountInfo.UserName;
844
                var container = cloudFile.Container ?? FolderConstants.PithosContainer;
845

    
846
                var client = new CloudFilesClient(accountInfo);
847
                //Even if GetObjectInfo times out, we can proceed with the upload            
848
                var info = client.GetObjectInfo(account, container, url);                
849
                var cloudHash = info.Hash.ToLower();
850

    
851
                var hash = action.LocalHash.Value;
852
                var topHash = action.TopHash.Value;
853

    
854
                //If the file hashes match, abort the upload
855
                if (hash == cloudHash  || topHash ==cloudHash)
856
                {
857
                    //but store any metadata changes 
858
                    this.StatusKeeper.StoreInfo(fullFileName, info);
859
                    Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
860
                    yield break;
861
                }
862

    
863
                if (info.AllowedTo=="read")
864
                    yield break;
865

    
866
                //Mark the file as modified while we upload it
867
                StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
868
                //And then upload it
869

    
870
                //Upload even small files using the Hashmap. The server may already containt
871
                //the relevant folder
872

    
873
                //First, calculate the tree hash
874
                var treeHash = Signature.CalculateTreeHashAsync(fileInfo.FullName, accountInfo.BlockSize,
875
                    accountInfo.BlockHash);
876
                yield return treeHash;
877
                    
878
                yield return Task.Factory.Iterate(UploadWithHashMap(accountInfo,cloudFile,fileInfo,url,treeHash));
879

    
880
                //If everything succeeds, change the file and overlay status to normal
881
                this.StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
882
            }
883
            //Notify the Shell to update the overlays
884
            NativeMethods.RaiseChangeNotification(fullFileName);
885
            StatusNotification.NotifyChangedFile(fullFileName);
886
        }
887

    
888
        public IEnumerable<Task> UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,Task<TreeHash> treeHash)
889
        {
890
            if (accountInfo == null)
891
                throw new ArgumentNullException("accountInfo");
892
            if (cloudFile==null)
893
                throw new ArgumentNullException("cloudFile");
894
            if (fileInfo == null)
895
                throw new ArgumentNullException("fileInfo");
896
            if (String.IsNullOrWhiteSpace(url))
897
                throw new ArgumentNullException(url);
898
            if (treeHash==null)
899
                throw new ArgumentNullException("treeHash");
900
            Contract.EndContractBlock();
901

    
902
            var fullFileName = fileInfo.FullName;
903

    
904
            var account = cloudFile.Account ?? accountInfo.UserName;
905
            var container = cloudFile.Container ?? FolderConstants.PithosContainer;
906

    
907
            var client = new CloudFilesClient(accountInfo);
908
            //Send the hashmap to the server            
909
            var hashPut = client.PutHashMap(account, container, url, treeHash.Result);
910
            yield return hashPut;
911

    
912
            var missingHashes = hashPut.Result;
913
            //If the server returns no missing hashes, we are done
914
            while (missingHashes.Count > 0)
915
            {
916

    
917
                var buffer = new byte[accountInfo.BlockSize];
918
                foreach (var missingHash in missingHashes)
919
                {
920
                    //Find the proper block
921
                    var blockIndex = treeHash.Result.HashDictionary[missingHash];
922
                    var offset = blockIndex*accountInfo.BlockSize;
923

    
924
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
925

    
926
                    //And upload the block                
927
                    var postBlock = client.PostBlock(account, container, buffer, 0, read);
928

    
929
                    //We have to handle possible exceptions in a continuation because
930
                    //*yield return* can't appear inside a try block
931
                    yield return postBlock.ContinueWith(t => 
932
                        t.ReportExceptions(
933
                            exc => Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc),
934
                            ()=>Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex,fullFileName)));
935
                }
936

    
937
                //Repeat until there are no more missing hashes
938
                hashPut = client.PutHashMap(account, container, url, treeHash.Result);
939
                yield return hashPut;
940
                missingHashes = hashPut.Result;
941
            }
942
        }
943

    
944

    
945
        public void AddAccount(AccountInfo accountInfo)
946
        {            
947
            if (!_accounts.Contains(accountInfo))
948
                _accounts.Add(accountInfo);
949
        }
950
    }
951

    
952
   
953

    
954

    
955
}