Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 8a84d039

History | View | Annotate | Download (56.2 kB)

1
// -----------------------------------------------------------------------
2
// <copyright file="NetworkAgent.cs" company="GRNET">
3
// Copyright 2011 GRNET S.A. All rights reserved.
4
// 
5
// Redistribution and use in source and binary forms, with or
6
// without modification, are permitted provided that the following
7
// conditions are met:
8
// 
9
//   1. Redistributions of source code must retain the above
10
//      copyright notice, this list of conditions and the following
11
//      disclaimer.
12
// 
13
//   2. Redistributions in binary form must reproduce the above
14
//      copyright notice, this list of conditions and the following
15
//      disclaimer in the documentation and/or other materials
16
//      provided with the distribution.
17
// 
18
// THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
// POSSIBILITY OF SUCH DAMAGE.
30
// 
31
// The views and conclusions contained in the software and
32
// documentation are those of the authors and should not be
33
// interpreted as representing official policies, either expressed
34
// or implied, of GRNET S.A.
35
// </copyright>
36
// -----------------------------------------------------------------------
37

    
38
using System;
39
using System.Collections.Concurrent;
40
using System.Collections.Generic;
41
using System.ComponentModel.Composition;
42
using System.Diagnostics;
43
using System.Diagnostics.Contracts;
44
using System.IO;
45
using System.Linq;
46
using System.Net;
47
using System.Threading;
48
using System.Threading.Tasks;
49
using System.Threading.Tasks.Dataflow;
50
using Castle.ActiveRecord;
51
using Pithos.Interfaces;
52
using Pithos.Network;
53
using log4net;
54

    
55
namespace Pithos.Core.Agents
56
{
57
    //TODO: Ensure all network operations use exact casing. Pithos is case sensitive
58
    [Export]
59
    public class NetworkAgent
60
    {
61
        private Agent<CloudAction> _agent;
62

    
63
        //A separate agent is used to execute delete actions immediatelly;
64
        private ActionBlock<CloudDeleteAction> _deleteAgent;
65
        readonly ConcurrentDictionary<string,DateTime> _deletedFiles=new ConcurrentDictionary<string, DateTime>();
66

    
67

    
68
        private readonly ManualResetEventSlim _pauseAgent = new ManualResetEventSlim(true);
69

    
70
        [System.ComponentModel.Composition.Import]
71
        public IStatusKeeper StatusKeeper { get; set; }
72
        
73
        public IStatusNotification StatusNotification { get; set; }
74

    
75
        private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
76

    
77
        private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
78

    
79
        [System.ComponentModel.Composition.Import]
80
        public IPithosSettings Settings { get; set; }
81

    
82
        private bool _firstPoll = true;
83
        private TaskCompletionSource<bool> _tcs;
84

    
85
        public void Start()
86
        {
87
            _firstPoll = true;
88
            _agent = Agent<CloudAction>.Start(inbox =>
89
            {
90
                Action loop = null;
91
                loop = () =>
92
                {
93
                    _pauseAgent.Wait();
94
                    var message = inbox.Receive();
95
                    var process=message.Then(Process,inbox.CancellationToken);
96
                    inbox.LoopAsync(process, loop);
97
                };
98
                loop();
99
            });
100

    
101
            _deleteAgent = new ActionBlock<CloudDeleteAction>(message =>ProcessDelete(message),new ExecutionDataflowBlockOptions{MaxDegreeOfParallelism=4});
102
            /*
103
                Action loop = null;
104
                loop = () =>
105
                            {
106
                                var message = inbox.Receive();
107
                                var process = message.Then(ProcessDelete,inbox.CancellationToken);
108
                                inbox.LoopAsync(process, loop);
109
                            };
110
                loop();
111
*/
112

    
113
        }
114

    
115
        private async Task Process(CloudAction action)
116
        {
117
            if (action == null)
118
                throw new ArgumentNullException("action");
119
            if (action.AccountInfo==null)
120
                throw new ArgumentException("The action.AccountInfo is empty","action");
121
            Contract.EndContractBlock();
122

    
123
            var accountInfo = action.AccountInfo;
124

    
125
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
126
            {                
127
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
128

    
129
                var cloudFile = action.CloudFile;
130
                var downloadPath = action.GetDownloadPath();
131

    
132
                try
133
                {
134

    
135
                    if (action.Action == CloudActionType.DeleteCloud)
136
                    {
137
                        //Redirect deletes to the delete agent 
138
                        _deleteAgent.Post((CloudDeleteAction)action);                        
139
                    }
140
                    if (IsDeletedFile(action))
141
                    {
142
                        //Clear the status of already deleted files to avoid reprocessing
143
                        if (action.LocalFile != null)
144
                            this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
145
                    }
146
                    else
147
                    {
148
                        switch (action.Action)
149
                        {
150
                            case CloudActionType.UploadUnconditional:
151
                                //Abort if the file was deleted before we reached this point
152
                                await UploadCloudFile(action);
153
                                break;
154
                            case CloudActionType.DownloadUnconditional:
155
                                await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
156
                                break;
157
                            case CloudActionType.RenameCloud:
158
                                var moveAction = (CloudMoveAction) action;
159
                                RenameCloudFile(accountInfo, moveAction);
160
                                break;
161
                            case CloudActionType.MustSynch:
162
                                if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
163
                                {
164
                                    await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
165
                                }
166
                                else
167
                                {
168
                                    await SyncFiles(accountInfo, action);
169
                                }
170
                                break;
171
                        }
172
                    }
173
                    Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
174
                                           action.CloudFile.Name);
175
                }
176
                catch (WebException exc)
177
                {
178
                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
179
                }
180
                catch (OperationCanceledException)
181
                {
182
                    throw;
183
                }
184
                catch (DirectoryNotFoundException)
185
                {
186
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
187
                        action.Action, action.LocalFile, action.CloudFile);
188
                    //Post a delete action for the missing file
189
                    Post(new CloudDeleteAction(action));                    
190
                }
191
                catch (FileNotFoundException)
192
                {
193
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
194
                        action.Action, action.LocalFile, action.CloudFile);
195
                    //Post a delete action for the missing file
196
                    Post(new CloudDeleteAction(action));
197
                }
198
                catch (Exception exc)
199
                {
200
                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
201
                                     action.Action, action.LocalFile, action.CloudFile, exc);
202

    
203
                    _agent.Post(action);
204
                }                
205
            }
206
        }
207

    
208
        /// <summary>
209
        /// Processes cloud delete actions
210
        /// </summary>
211
        /// <param name="action">The delete action to execute</param>
212
        /// <returns></returns>
213
        /// <remarks>
214
        /// When a file/folder is deleted locally, we must delete it ASAP from the server and block any download
215
        /// operations that may be in progress.
216
        /// <para>
217
        /// A separate agent is used to process deletes because the main agent may be busy with a long operation.
218
        /// </para>
219
        /// </remarks>
220
        private async Task ProcessDelete(CloudDeleteAction action)
221
        {
222
            if (action == null)
223
                throw new ArgumentNullException("action");
224
            if (action.AccountInfo==null)
225
                throw new ArgumentException("The action.AccountInfo is empty","action");
226
            Contract.EndContractBlock();
227

    
228
            var accountInfo = action.AccountInfo;
229

    
230
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
231
            {                
232
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
233

    
234
                var cloudFile = action.CloudFile;
235

    
236
                try
237
                {
238
                    //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
239
                    //agent
240
                    using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
241
                    {
242

    
243
                        //Add the file URL to the deleted files list
244
                        var key = GetFileKey(action.CloudFile);
245
                        _deletedFiles[key] = DateTime.Now;
246

    
247
                        _pauseAgent.Reset();
248
                        // and then delete the file from the server
249
                        DeleteCloudFile(accountInfo, cloudFile);
250

    
251
                        Log.InfoFormat("[ACTION] End Delete {0}:{1}->{2}", action.Action, action.LocalFile,
252
                                       action.CloudFile.Name);
253
                    }
254
                }
255
                catch (WebException exc)
256
                {
257
                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
258
                }
259
                catch (OperationCanceledException)
260
                {
261
                    throw;
262
                }
263
                catch (DirectoryNotFoundException)
264
                {
265
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
266
                        action.Action, action.LocalFile, action.CloudFile);
267
                    //Repost a delete action for the missing file
268
                    _deleteAgent.Post(action);
269
                }
270
                catch (FileNotFoundException)
271
                {
272
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
273
                        action.Action, action.LocalFile, action.CloudFile);
274
                    //Post a delete action for the missing file
275
                    _deleteAgent.Post(action);
276
                }
277
                catch (Exception exc)
278
                {
279
                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
280
                                     action.Action, action.LocalFile, action.CloudFile, exc);
281

    
282
                    _deleteAgent.Post(action);
283
                }
284
                finally
285
                {
286
                    if (_deleteAgent.InputCount == 0)
287
                        _pauseAgent.Set();
288

    
289
                }
290
            }
291
        }
292

    
293
        private static string GetFileKey(ObjectInfo info)
294
        {
295
            var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
296
            return key;
297
        }
298

    
299
        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
300
        {
301
            if (accountInfo == null)
302
                throw new ArgumentNullException("accountInfo");
303
            if (action==null)
304
                throw new ArgumentNullException("action");
305
            if (action.LocalFile==null)
306
                throw new ArgumentException("The action's local file is not specified","action");
307
            if (!Path.IsPathRooted(action.LocalFile.FullName))
308
                throw new ArgumentException("The action's local file path must be absolute","action");
309
            if (action.CloudFile== null)
310
                throw new ArgumentException("The action's cloud file is not specified", "action");
311
            Contract.EndContractBlock();
312

    
313
            var localFile = action.LocalFile;
314
            var cloudFile = action.CloudFile;
315
            var downloadPath=action.LocalFile.GetProperCapitalization();
316

    
317
            var cloudHash = cloudFile.Hash.ToLower();
318
            var localHash = action.LocalHash.Value.ToLower();
319
            var topHash = action.TopHash.Value.ToLower();
320

    
321
            //Not enough to compare only the local hashes, also have to compare the tophashes
322
            
323
            //If any of the hashes match, we are done
324
            if ((cloudHash == localHash || cloudHash == topHash))
325
            {
326
                Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
327
                return;
328
            }
329

    
330
            //The hashes DON'T match. We need to sync
331
            var lastLocalTime = localFile.LastWriteTime;
332
            var lastUpTime = cloudFile.Last_Modified;
333
            
334
            //If the local file is newer upload it
335
            if (lastUpTime <= lastLocalTime)
336
            {
337
                //It probably means it was changed while the app was down                        
338
                UploadCloudFile(action);
339
            }
340
            else
341
            {
342
                //It the cloud file has a later date, it was modified by another user or computer.
343
                //We need to check the local file's status                
344
                var status = StatusKeeper.GetFileStatus(downloadPath);
345
                switch (status)
346
                {
347
                    case FileStatus.Unchanged:                        
348
                        //If the local file's status is Unchanged, we can go on and download the newer cloud file
349
                        await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
350
                        break;
351
                    case FileStatus.Modified:
352
                        //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
353
                        //We can't ensure that a file modified online since the last time will appear as Modified, unless we 
354
                        //index all files before we start listening.                       
355
                    case FileStatus.Created:
356
                        //If the local file is Created, it means that the local and cloud files aren't related,
357
                        // yet they have the same name.
358

    
359
                        //In both cases we must mark the file as in conflict
360
                        ReportConflict(downloadPath);
361
                        break;
362
                    default:
363
                        //Other cases should never occur. Mark them as Conflict as well but log a warning
364
                        ReportConflict(downloadPath);
365
                        Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
366
                                       downloadPath, action.CloudFile.Name);
367
                        break;
368
                }
369
            }
370
        }
371

    
372
        private void ReportConflict(string downloadPath)
373
        {
374
            if (String.IsNullOrWhiteSpace(downloadPath))
375
                throw new ArgumentNullException("downloadPath");
376
            Contract.EndContractBlock();
377

    
378
            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
379
            var message = String.Format("Conflict detected for file {0}", downloadPath);
380
            Log.Warn(message);
381
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
382
        }
383

    
384
        public void Post(CloudAction cloudAction)
385
        {
386
            if (cloudAction == null)
387
                throw new ArgumentNullException("cloudAction");
388
            if (cloudAction.AccountInfo==null)
389
                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
390
            Contract.EndContractBlock();
391

    
392
            _pauseAgent.Wait();
393

    
394
            //If the action targets a local file, add a treehash calculation
395
            if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
396
            {
397
                var accountInfo = cloudAction.AccountInfo;
398
                var localFile = (FileInfo) cloudAction.LocalFile;
399
                if (localFile.Length > accountInfo.BlockSize)
400
                    cloudAction.TopHash =
401
                        new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
402
                                                                                accountInfo.BlockSize,
403
                                                                                accountInfo.BlockHash).Result
404
                                                    .TopHash.ToHashString());
405
                else
406
                {
407
                    cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
408
                }
409
            }
410
            else
411
            {
412
                //The hash for a directory is the empty string
413
                cloudAction.TopHash = new Lazy<string>(() => String.Empty);
414
            }
415
            
416
            if (cloudAction is CloudDeleteAction)
417
                _deleteAgent.Post((CloudDeleteAction)cloudAction);
418
            else
419
                _agent.Post(cloudAction);
420
        }
421

    
422
       /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
423
        {
424
            public bool Equals(ObjectInfo x, ObjectInfo y)
425
            {
426
                return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
427
            }
428

    
429
            public int GetHashCode(ObjectInfo obj)
430
            {
431
                return obj.Name.ToLower().GetHashCode();
432
            }
433
        }*/
434

    
435
        public void SynchNow()
436
        {             
437
            if (_tcs!=null)
438
                _tcs.SetResult(true);
439
            else
440
            {
441
                //TODO: This may be OK for testing purposes, but we have no guarantee that it will
442
                //work properly in production
443
                PollRemoteFiles(repeat:false);
444
            }
445
        }
446

    
447
        //Remote files are polled periodically. Any changes are processed
448
        public async Task PollRemoteFiles(DateTime? since = null,bool repeat=true)
449
        {
450

    
451
            _tcs = new TaskCompletionSource<bool>();
452
            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
453
            var signaledTask=await TaskEx.WhenAny(_tcs.Task,wait);
454
            //If polling is signalled by SynchNow, ignore the since tag
455
            if (signaledTask is Task<bool>)
456
                since = null;
457

    
458
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
459
            {
460

    
461
                try
462
                {
463
                    //Next time we will check for all changes since the current check minus 1 second
464
                    //This is done to ensure there are no discrepancies due to clock differences
465
                    DateTime nextSince = DateTime.Now.AddSeconds(-1);
466

    
467
                    var tasks = from accountInfo in _accounts
468
                                select ProcessAccountFiles(accountInfo, since);
469

    
470
                    await TaskEx.WhenAll(tasks.ToList());
471

    
472
                    _firstPoll = false;
473
                    if (repeat)
474
                        PollRemoteFiles(nextSince);
475
                }
476
                catch (Exception ex)
477
                {
478
                    Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
479
                    //In case of failure retry with the same parameter
480
                    PollRemoteFiles(since);
481
                }
482
                
483

    
484
            }
485
        }
486

    
487
        public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
488
        {   
489
            if (accountInfo==null)
490
                throw new ArgumentNullException("accountInfo");
491
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
492
                throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
493
            Contract.EndContractBlock();
494

    
495
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
496
            {
497
                Log.Info("Scheduled");
498
                var client=new CloudFilesClient(accountInfo);
499

    
500
                var containers = client.ListContainers(accountInfo.UserName);
501
                
502
                CreateContainerFolders(accountInfo, containers);
503

    
504
                try
505
                {
506
                    _pauseAgent.Wait();
507
                    //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
508
                    //than delete a file that was created while we were executing the poll
509
                    var pollTime = DateTime.Now;
510
                    
511
                    //Get the list of server objects changed since the last check
512
                    //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
513
                    var listObjects = from container in containers
514
                                      select  Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
515
                                            client.ListObjects(accountInfo.UserName,container.Name, since),container.Name);
516

    
517

    
518
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
519

    
520
                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
521
                    {
522
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
523

    
524
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
525
                        var remoteObjects = from objectList in listTasks
526
                                            where (string) objectList.AsyncState != "trash"
527
                                            from obj in objectList.Result
528
                                            select obj;
529

    
530
                        //TODO: Change the way deleted objects are detected.
531
                        //The list operation returns all existing objects so we could detect deleted remote objects
532
                        //by detecting objects that exist only locally. There are several cases where this is NOT the case:
533
                        //1.    The first time the application runs, as there may be files that were added while 
534
                        //      the application was down.
535
                        //2.    An object that is currently being uploaded will not appear in the remote list
536
                        //      until the upload finishes.
537
                        //      SOLUTION 1: Check the upload/download queue for the file
538
                        //      SOLUTION 2: Check the SQLite states for the file's entry. If it is being uploaded, 
539
                        //          or its last modification was after the current poll, don't delete it. This way we don't
540
                        //          delete objects whose upload finished too late to be included in the list.
541
                        //We need to detect and protect against such situations
542
                        //TODO: Does FileState have a LastModification field?
543
                        //TODO: How do we update the LastModification field? Do we need to add SQLite triggers?
544
                        //      Do we need to use a proper SQLite schema?
545
                        //      We can create a trigger with 
546
                        // CREATE TRIGGER IF NOT EXISTS update_last_modified UPDATE ON FileState FOR EACH ROW
547
                        //  BEGIN
548
                        //      UPDATE FileState SET LastModification=datetime('now')  WHERE Id=old.Id;
549
                        //  END;
550
                        //
551
                        //NOTE: Some files may have been deleted remotely while the application was down. 
552
                        //  We DO have to delete those files. Checking the trash makes it easy to detect them,
553
                        //  Otherwise, we can't be really sure whether we need to upload or delete 
554
                        //  the local-only files.
555
                        //  SOLUTION 1: Ask the user when such a local-only file is detected during the first poll.
556
                        //  SOLUTION 2: Mark conflict and ask the user as in #1
557

    
558
                        var trashObjects = dict["trash"].Result;
559
                        //var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
560

    
561
                        //Items with the same name, hash may be both in the container and the trash
562
                        //Don't delete items that exist in the container
563
                        var realTrash = from trash in trashObjects
564
                                        where
565
                                            !remoteObjects.Any(
566
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
567
                                        select trash;
568
                        ProcessTrashedFiles(accountInfo, realTrash);
569

    
570

    
571
                        var cleanRemotes = (from info in remoteObjects
572
                                     //.Union(sharedObjects)
573
                                     let name = info.Name
574
                                     where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
575
                                           !name.StartsWith(FolderConstants.CacheFolder + "/",
576
                                                            StringComparison.InvariantCultureIgnoreCase)
577
                                     select info).ToList();
578

    
579

    
580

    
581
                        ProcessDeletedFiles(accountInfo, cleanRemotes, pollTime);
582

    
583
                        //Create a list of actions from the remote files
584
                        var allActions = ObjectsToActions(accountInfo, cleanRemotes);
585

    
586
                        
587
                        //var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
588

    
589
                        //And remove those that are already being processed by the agent
590
                        var distinctActions = allActions
591
                            .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
592
                            .ToList();
593

    
594
                        //Queue all the actions
595
                        foreach (var message in distinctActions)
596
                        {
597
                            Post(message);
598
                        }
599

    
600
                        Log.Info("[LISTENER] End Processing");
601
                    }
602
                }
603
                catch (Exception ex)
604
                {
605
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
606
                    return;
607
                }
608

    
609
                Log.Info("[LISTENER] Finished");
610

    
611
            }
612
        }
613

    
614
        /// <summary>
615
        /// Deletes local files that are not found in the list of cloud files
616
        /// </summary>
617
        /// <param name="accountInfo"></param>
618
        /// <param name="cloudFiles"></param>
619
        /// <param name="pollTime"></param>
620
        private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
621
        {
622
            if (accountInfo == null)
623
                throw new ArgumentNullException("accountInfo");
624
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
625
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
626
            if (cloudFiles == null)
627
                throw new ArgumentNullException("cloudFiles");
628
            Contract.EndContractBlock();
629

    
630
            if (_firstPoll) return;
631
            //TODO: Do I need the "Modified" check if I'm not going to delete files that
632
            //were not found on the server on the first run?
633
            //TODO: Files that were not found on the server on the first run should be marked IN CONFLICT
634
            var deleteCandidates = from state in FileState.Queryable
635
                                   where state.Modified <= pollTime && state.FilePath.StartsWith(accountInfo.AccountPath)
636
                                   select state;
637

    
638
            foreach (var deleteCandidate in deleteCandidates)
639
            {
640
                var localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath);
641
                var relativeFilePath=localFile.AsRelativeTo(accountInfo.AccountPath);
642
                if (!cloudFiles.Any(r => Path.Combine(r.Container, r.Name) == relativeFilePath))
643
                {
644
                    localFile.Delete();
645
                    StatusKeeper.ClearFileStatus(deleteCandidate.FilePath);
646
                }
647
            }
648
        }
649

    
650
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
651
        {
652
            var containerPaths = from container in containers
653
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
654
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
655
                                 select containerPath;
656

    
657
            foreach (var path in containerPaths)
658
            {
659
                Directory.CreateDirectory(path);
660
            }
661
        }
662

    
663
        //Creates an appropriate action for each server file
664
        private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
665
        {
666
            if (remote==null)
667
                throw new ArgumentNullException();
668
            Contract.EndContractBlock();
669
            var fileAgent = GetFileAgent(accountInfo);
670

    
671
            //In order to avoid multiple iterations over the files, we iterate only once
672
            //over the remote files
673
            foreach (var objectInfo in remote)
674
            {
675
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
676
                //and remove any matching objects from the list, adding them to the commonObjects list
677
                
678
                if (fileAgent.Exists(relativePath))
679
                {
680
                    //If a directory object already exists, we don't need to perform any other action                    
681
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
682
                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
683
                        continue;
684
                    using (new SessionScope(FlushAction.Never))
685
                    {
686
                        var state =  StatusKeeper.GetStateByFilePath(localFile.FullName);
687
                        //FileState.FindByFilePath(localFile.FullName);
688
                        //Common files should be checked on a per-case basis to detect differences, which is newer
689

    
690
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
691
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
692
                                                     accountInfo.BlockHash);
693
                    }
694
                }
695
                else
696
                {
697
                    //If there is no match we add them to the localFiles list
698
                    //but only if the file is not marked for deletion
699
                    var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
700
                    var fileStatus = StatusKeeper.GetFileStatus(targetFile);
701
                    if (fileStatus != FileStatus.Deleted)
702
                    {
703
                        //Remote files should be downloaded
704
                        yield return new CloudDownloadAction(accountInfo,objectInfo);
705
                    }
706
                }
707
            }            
708
        }
709

    
710
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
711
        {
712
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
713
        }
714

    
715
        private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
716
        {
717
            var fileAgent = GetFileAgent(accountInfo);
718
            foreach (var trashObject in trashObjects)
719
            {
720
                var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
721
                //HACK: Assume only the "pithos" container is used. Must find out what happens when
722
                //deleting a file from a different container
723
                var relativePath = Path.Combine("pithos", barePath);
724
                fileAgent.Delete(relativePath);                                
725
            }
726
        }
727

    
728

    
729
        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
730
        {
731
            if (accountInfo==null)
732
                throw new ArgumentNullException("accountInfo");
733
            if (action==null)
734
                throw new ArgumentNullException("action");
735
            if (action.CloudFile==null)
736
                throw new ArgumentException("CloudFile","action");
737
            if (action.LocalFile==null)
738
                throw new ArgumentException("LocalFile","action");
739
            if (action.OldLocalFile==null)
740
                throw new ArgumentException("OldLocalFile","action");
741
            if (action.OldCloudFile==null)
742
                throw new ArgumentException("OldCloudFile","action");
743
            Contract.EndContractBlock();
744
            
745
            
746
            var newFilePath = action.LocalFile.FullName;
747
            
748
            //How do we handle concurrent renames and deletes/uploads/downloads?
749
            //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
750
            //  This should never happen as the network agent executes only one action at a time
751
            //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
752
            //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
753
            //  same name will fail.
754
            //  This should never happen as the network agent executes only one action at a time.
755
            //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
756
            //  to remove the rename from the queue.
757
            //  We can probably ignore this case. It will result in an error which should be ignored            
758

    
759
            
760
            //The local file is already renamed
761
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
762

    
763

    
764
            var account = action.CloudFile.Account ?? accountInfo.UserName;
765
            var container = action.CloudFile.Container;
766
            
767
            var client = new CloudFilesClient(accountInfo);
768
            //TODO: What code is returned when the source file doesn't exist?
769
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
770

    
771
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
772
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
773
            NativeMethods.RaiseChangeNotification(newFilePath);
774
        }
775

    
776
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
777
        {
778
            if (accountInfo == null)
779
                throw new ArgumentNullException("accountInfo");
780
            if (cloudFile==null)
781
                throw new ArgumentNullException("cloudFile");
782

    
783
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
784
                throw new ArgumentException("Invalid container", "cloudFile");
785
            Contract.EndContractBlock();
786
            
787
            var fileAgent = GetFileAgent(accountInfo);
788

    
789
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
790
            {
791
                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
792
                var info = fileAgent.GetFileSystemInfo(fileName);                
793
                var fullPath = info.FullName.ToLower();
794

    
795
                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
796

    
797
                var account = cloudFile.Account ?? accountInfo.UserName;
798
                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
799

    
800
                var client = new CloudFilesClient(accountInfo);
801
                client.DeleteObject(account, container, cloudFile.Name);
802

    
803
                StatusKeeper.ClearFileStatus(fullPath);
804
            }
805
        }
806

    
807
        //Download a file.
808
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
809
        {
810
            if (accountInfo == null)
811
                throw new ArgumentNullException("accountInfo");
812
            if (cloudFile == null)
813
                throw new ArgumentNullException("cloudFile");
814
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
815
                throw new ArgumentNullException("cloudFile");
816
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
817
                throw new ArgumentNullException("cloudFile");
818
            if (String.IsNullOrWhiteSpace(filePath))
819
                throw new ArgumentNullException("filePath");
820
            if (!Path.IsPathRooted(filePath))
821
                throw new ArgumentException("The filePath must be rooted", "filePath");
822
            Contract.EndContractBlock();
823

    
824
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
825
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
826

    
827
            var url = relativeUrl.ToString();
828
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
829
                return;
830

    
831

    
832
            //Are we already downloading or uploading the file? 
833
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
834
            {
835
                if (gate.Failed)
836
                    return;
837
                //The file's hashmap will be stored in the same location with the extension .hashmap
838
                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
839
                
840
                var client = new CloudFilesClient(accountInfo);
841
                var account = cloudFile.Account;
842
                var container = cloudFile.Container;
843

    
844
                if (cloudFile.Content_Type == @"application/directory")
845
                {
846
                    if (!Directory.Exists(localPath))
847
                        Directory.CreateDirectory(localPath);
848
                }
849
                else
850
                {
851
                    //Retrieve the hashmap from the server
852
                    var serverHash = await client.GetHashMap(account, container, url);
853
                    //If it's a small file
854
                    if (serverHash.Hashes.Count == 1)
855
                        //Download it in one go
856
                        await
857
                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
858
                        //Otherwise download it block by block
859
                    else
860
                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
861

    
862
                    if (cloudFile.AllowedTo == "read")
863
                    {
864
                        var attributes = File.GetAttributes(localPath);
865
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
866
                    }
867
                }
868

    
869
                //Now we can store the object's metadata without worrying about ghost status entries
870
                StatusKeeper.StoreInfo(localPath, cloudFile);
871
                
872
            }
873
        }
874

    
875
        //Download a small file with a single GET operation
876
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
877
        {
878
            if (client == null)
879
                throw new ArgumentNullException("client");
880
            if (cloudFile==null)
881
                throw new ArgumentNullException("cloudFile");
882
            if (relativeUrl == null)
883
                throw new ArgumentNullException("relativeUrl");
884
            if (String.IsNullOrWhiteSpace(filePath))
885
                throw new ArgumentNullException("filePath");
886
            if (!Path.IsPathRooted(filePath))
887
                throw new ArgumentException("The localPath must be rooted", "filePath");
888
            Contract.EndContractBlock();
889

    
890
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
891
            //If the file already exists
892
            if (File.Exists(localPath))
893
            {
894
                //First check with MD5 as this is a small file
895
                var localMD5 = Signature.CalculateMD5(localPath);
896
                var cloudHash=serverHash.TopHash.ToHashString();
897
                if (localMD5==cloudHash)
898
                    return;
899
                //Then check with a treehash
900
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
901
                var localHash = localTreeHash.TopHash.ToHashString();
902
                if (localHash==cloudHash)
903
                    return;
904
            }
905

    
906
            var fileAgent = GetFileAgent(accountInfo);
907
            //Calculate the relative file path for the new file
908
            var relativePath = relativeUrl.RelativeUriToFilePath();
909
            //The file will be stored in a temporary location while downloading with an extension .download
910
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
911
            //Make sure the target folder exists. DownloadFileTask will not create the folder
912
            var tempFolder = Path.GetDirectoryName(tempPath);
913
            if (!Directory.Exists(tempFolder))
914
                Directory.CreateDirectory(tempFolder);
915

    
916
            //Download the object to the temporary location
917
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
918

    
919
            //Create the local folder if it doesn't exist (necessary for shared objects)
920
            var localFolder = Path.GetDirectoryName(localPath);
921
            if (!Directory.Exists(localFolder))
922
                Directory.CreateDirectory(localFolder);            
923
            //And move it to its actual location once downloading is finished
924
            if (File.Exists(localPath))
925
                File.Replace(tempPath,localPath,null,true);
926
            else
927
                File.Move(tempPath,localPath);
928
            //Notify listeners that a local file has changed
929
            StatusNotification.NotifyChangedFile(localPath);
930

    
931
                       
932
        }
933

    
934
        //Download a file asynchronously using blocks
935
        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
936
        {
937
            if (client == null)
938
                throw new ArgumentNullException("client");
939
            if (cloudFile == null)
940
                throw new ArgumentNullException("cloudFile");
941
            if (relativeUrl == null)
942
                throw new ArgumentNullException("relativeUrl");
943
            if (String.IsNullOrWhiteSpace(filePath))
944
                throw new ArgumentNullException("filePath");
945
            if (!Path.IsPathRooted(filePath))
946
                throw new ArgumentException("The filePath must be rooted", "filePath");
947
            if (serverHash == null)
948
                throw new ArgumentNullException("serverHash");
949
            Contract.EndContractBlock();
950
            
951
           var fileAgent = GetFileAgent(accountInfo);
952
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
953
            
954
            //Calculate the relative file path for the new file
955
            var relativePath = relativeUrl.RelativeUriToFilePath();
956
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
957

    
958
            
959
                        
960
            //Calculate the file's treehash
961
            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
962
                
963
            //And compare it with the server's hash
964
            var upHashes = serverHash.GetHashesAsStrings();
965
            var localHashes = treeHash.HashDictionary;
966
            for (int i = 0; i < upHashes.Length; i++)
967
            {
968
                //For every non-matching hash
969
                var upHash = upHashes[i];
970
                if (!localHashes.ContainsKey(upHash))
971
                {
972
                    if (blockUpdater.UseOrphan(i, upHash))
973
                    {
974
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
975
                        continue;
976
                    }
977
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
978
                    var start = i*serverHash.BlockSize;
979
                    //To download the last block just pass a null for the end of the range
980
                    long? end = null;
981
                    if (i < upHashes.Length - 1 )
982
                        end= ((i + 1)*serverHash.BlockSize) ;
983
                            
984
                    //Download the missing block
985
                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
986

    
987
                    //and store it
988
                    blockUpdater.StoreBlock(i, block);
989

    
990

    
991
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
992
                }
993
            }
994

    
995
            //Want to avoid notifications if no changes were made
996
            var hasChanges = blockUpdater.HasBlocks;
997
            blockUpdater.Commit();
998
            
999
            if (hasChanges)
1000
                //Notify listeners that a local file has changed
1001
                StatusNotification.NotifyChangedFile(localPath);
1002

    
1003
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
1004
        }
1005

    
1006

    
1007
        private async Task UploadCloudFile(CloudAction action)
1008
        {
1009
            if (action == null)
1010
                throw new ArgumentNullException("action");           
1011
            Contract.EndContractBlock();
1012

    
1013
            try
1014
            {
1015
                var accountInfo = action.AccountInfo;
1016

    
1017
                var fileInfo = action.LocalFile;
1018

    
1019
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
1020
                    return;
1021
                
1022
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
1023
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
1024
                {
1025
                    var parts = relativePath.Split('\\');
1026
                    var accountName = parts[1];
1027
                    var oldName = accountInfo.UserName;
1028
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
1029
                    var nameIndex = absoluteUri.IndexOf(oldName);
1030
                    var root = absoluteUri.Substring(0, nameIndex);
1031

    
1032
                    accountInfo = new AccountInfo
1033
                    {
1034
                        UserName = accountName,
1035
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
1036
                        StorageUri = new Uri(root + accountName),
1037
                        BlockHash = accountInfo.BlockHash,
1038
                        BlockSize = accountInfo.BlockSize,
1039
                        Token = accountInfo.Token
1040
                    };
1041
                }
1042

    
1043

    
1044
                var fullFileName = fileInfo.GetProperCapitalization();
1045
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
1046
                {
1047
                    //Abort if the file is already being uploaded or downloaded
1048
                    if (gate.Failed)
1049
                        return;
1050

    
1051
                    var cloudFile = action.CloudFile;
1052
                    var account = cloudFile.Account ?? accountInfo.UserName;
1053

    
1054
                    var client = new CloudFilesClient(accountInfo);                    
1055
                    //Even if GetObjectInfo times out, we can proceed with the upload            
1056
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
1057

    
1058
                    //If this is a read-only file, do not upload changes
1059
                    if (info.AllowedTo == "read")
1060
                        return;
1061
                    
1062
                    //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
1063
                    if (fileInfo is DirectoryInfo)
1064
                    {
1065
                        //If the directory doesn't exist the Hash property will be empty
1066
                        if (String.IsNullOrWhiteSpace(info.Hash))
1067
                            //Go on and create the directory
1068
                            await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
1069
                    }
1070
                    else
1071
                    {
1072

    
1073
                        var cloudHash = info.Hash.ToLower();
1074

    
1075
                        var hash = action.LocalHash.Value;
1076
                        var topHash = action.TopHash.Value;
1077

    
1078
                        //If the file hashes match, abort the upload
1079
                        if (hash == cloudHash || topHash == cloudHash)
1080
                        {
1081
                            //but store any metadata changes 
1082
                            StatusKeeper.StoreInfo(fullFileName, info);
1083
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1084
                            return;
1085
                        }
1086

    
1087

    
1088
                        //Mark the file as modified while we upload it
1089
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1090
                        //And then upload it
1091

    
1092
                        //Upload even small files using the Hashmap. The server may already contain
1093
                        //the relevant block
1094

    
1095
                        //First, calculate the tree hash
1096
                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1097
                                                                              accountInfo.BlockHash);
1098

    
1099
                        await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1100
                    }
1101
                    //If everything succeeds, change the file and overlay status to normal
1102
                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1103
                }
1104
                //Notify the Shell to update the overlays
1105
                NativeMethods.RaiseChangeNotification(fullFileName);
1106
                StatusNotification.NotifyChangedFile(fullFileName);
1107
            }
1108
            catch (AggregateException ex)
1109
            {
1110
                var exc = ex.InnerException as WebException;
1111
                if (exc == null)
1112
                    throw ex.InnerException;
1113
                if (HandleUploadWebException(action, exc)) 
1114
                    return;
1115
                throw;
1116
            }
1117
            catch (WebException ex)
1118
            {
1119
                if (HandleUploadWebException(action, ex))
1120
                    return;
1121
                throw;
1122
            }
1123
            catch (Exception ex)
1124
            {
1125
                Log.Error("Unexpected error while uploading file", ex);
1126
                throw;
1127
            }
1128

    
1129
        }
1130

    
1131
        private bool IsDeletedFile(CloudAction action)
1132
        {            
1133
            var key = GetFileKey(action.CloudFile);
1134
            DateTime entryDate;
1135
            if (_deletedFiles.TryGetValue(key, out entryDate))
1136
            {
1137
                //If the delete entry was created after this action, abort the action
1138
                if (entryDate > action.Created)
1139
                    return true;
1140
                //Otherwise, remove the stale entry 
1141
                _deletedFiles.TryRemove(key, out entryDate);
1142
            }
1143
            return false;
1144
        }
1145

    
1146
        private bool HandleUploadWebException(CloudAction action, WebException exc)
1147
        {
1148
            var response = exc.Response as HttpWebResponse;
1149
            if (response == null)
1150
                throw exc;
1151
            if (response.StatusCode == HttpStatusCode.Unauthorized)
1152
            {
1153
                Log.Error("Not allowed to upload file", exc);
1154
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1155
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1156
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
1157
                return true;
1158
            }
1159
            return false;
1160
        }
1161

    
1162
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1163
        {
1164
            if (accountInfo == null)
1165
                throw new ArgumentNullException("accountInfo");
1166
            if (cloudFile==null)
1167
                throw new ArgumentNullException("cloudFile");
1168
            if (fileInfo == null)
1169
                throw new ArgumentNullException("fileInfo");
1170
            if (String.IsNullOrWhiteSpace(url))
1171
                throw new ArgumentNullException(url);
1172
            if (treeHash==null)
1173
                throw new ArgumentNullException("treeHash");
1174
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1175
                throw new ArgumentException("Invalid container","cloudFile");
1176
            Contract.EndContractBlock();
1177

    
1178
            var fullFileName = fileInfo.GetProperCapitalization();
1179

    
1180
            var account = cloudFile.Account ?? accountInfo.UserName;
1181
            var container = cloudFile.Container ;
1182

    
1183
            var client = new CloudFilesClient(accountInfo);
1184
            //Send the hashmap to the server            
1185
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
1186
            //If the server returns no missing hashes, we are done
1187
            while (missingHashes.Count > 0)
1188
            {
1189

    
1190
                var buffer = new byte[accountInfo.BlockSize];
1191
                foreach (var missingHash in missingHashes)
1192
                {
1193
                    //Find the proper block
1194
                    var blockIndex = treeHash.HashDictionary[missingHash];
1195
                    var offset = blockIndex*accountInfo.BlockSize;
1196

    
1197
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1198

    
1199
                    try
1200
                    {
1201
                        //And upload the block                
1202
                        await client.PostBlock(account, container, buffer, 0, read);
1203
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1204
                    }
1205
                    catch (Exception exc)
1206
                    {
1207
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1208
                    }
1209

    
1210
                }
1211

    
1212
                //Repeat until there are no more missing hashes                
1213
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
1214
            }
1215
        }
1216

    
1217

    
1218
        public void AddAccount(AccountInfo accountInfo)
1219
        {            
1220
            if (!_accounts.Contains(accountInfo))
1221
                _accounts.Add(accountInfo);
1222
        }
1223
    }
1224

    
1225
   
1226

    
1227

    
1228
}