Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 025046f1

History | View | Annotate | Download (58.8 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

    
452
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
453
            {
454
                //If this poll fails, we will retry with the same since value
455
                var nextSince = since;
456
                try
457
                {
458
                    //Next time we will check for all changes since the current check minus 1 second
459
                    //This is done to ensure there are no discrepancies due to clock differences
460
                    DateTime current = DateTime.Now.AddSeconds(-1);
461

    
462
                    var tasks = from accountInfo in _accounts
463
                                select ProcessAccountFiles(accountInfo, since);
464

    
465
                    await TaskEx.WhenAll(tasks.ToList());
466
                                        
467
                    _firstPoll = false;
468
                    //Reschedule the poll with the current timestamp as a "since" value
469
                    if (repeat)
470
                        nextSince = current;
471
                    else
472
                        return;
473
                }
474
                catch (Exception ex)
475
                {
476
                    Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
477
                    //In case of failure retry with the same "since" value
478
                }
479

    
480
                //Wait for the polling interval to pass or the Manual flat to be toggled
481
                nextSince = await WaitForScheduledOrManualPoll(nextSince);
482

    
483
                PollRemoteFiles(nextSince);
484

    
485
            }
486
        }
487

    
488
        private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
489
        {            
490
            _tcs = new TaskCompletionSource<bool>();
491
            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
492
            var signaledTask = await TaskEx.WhenAny(_tcs.Task, wait);
493
            //If polling is signalled by SynchNow, ignore the since tag
494
            if (signaledTask is Task<bool>)
495
                return null;
496
            return since;
497
        }
498

    
499
        public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
500
        {   
501
            if (accountInfo==null)
502
                throw new ArgumentNullException("accountInfo");
503
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
504
                throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
505
            Contract.EndContractBlock();
506

    
507
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
508
            {
509
                Log.Info("Scheduled");
510
                var client=new CloudFilesClient(accountInfo);
511

    
512
                var containers = client.ListContainers(accountInfo.UserName);
513
                
514
                CreateContainerFolders(accountInfo, containers);
515

    
516
                try
517
                {
518
                    _pauseAgent.Wait();
519
                    //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
520
                    //than delete a file that was created while we were executing the poll
521
                    var pollTime = DateTime.Now;
522
                    
523
                    //Get the list of server objects changed since the last check
524
                    //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
525
                    var listObjects = from container in containers
526
                                      select  Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
527
                                            client.ListObjects(accountInfo.UserName,container.Name, since),container.Name);
528

    
529

    
530
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
531

    
532
                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
533
                    {
534
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
535

    
536
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
537
                        var remoteObjects = from objectList in listTasks
538
                                            where (string) objectList.AsyncState != "trash"
539
                                            from obj in objectList.Result
540
                                            select obj;
541

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

    
570
                        var trashObjects = dict["trash"].Result;
571
                        //var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
572

    
573
                        //Items with the same name, hash may be both in the container and the trash
574
                        //Don't delete items that exist in the container
575
                        var realTrash = from trash in trashObjects
576
                                        where
577
                                            !remoteObjects.Any(
578
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
579
                                        select trash;
580
                        ProcessTrashedFiles(accountInfo, realTrash);
581

    
582

    
583
                        var cleanRemotes = (from info in remoteObjects
584
                                     //.Union(sharedObjects)
585
                                     let name = info.Name
586
                                     where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
587
                                           !name.StartsWith(FolderConstants.CacheFolder + "/",
588
                                                            StringComparison.InvariantCultureIgnoreCase)
589
                                     select info).ToList();
590

    
591

    
592

    
593
                        ProcessDeletedFiles(accountInfo, cleanRemotes, pollTime);
594

    
595
                        //Create a list of actions from the remote files
596
                        var allActions = ObjectsToActions(accountInfo, cleanRemotes);
597

    
598
                        
599
                        //var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
600

    
601
                        //And remove those that are already being processed by the agent
602
                        var distinctActions = allActions
603
                            .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
604
                            .ToList();
605

    
606
                        //Queue all the actions
607
                        foreach (var message in distinctActions)
608
                        {
609
                            Post(message);
610
                        }
611

    
612
                        Log.Info("[LISTENER] End Processing");
613
                    }
614
                }
615
                catch (Exception ex)
616
                {
617
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
618
                    return;
619
                }
620

    
621
                Log.Info("[LISTENER] Finished");
622

    
623
            }
624
        }
625

    
626
        /// <summary>
627
        /// Deletes local files that are not found in the list of cloud files
628
        /// </summary>
629
        /// <param name="accountInfo"></param>
630
        /// <param name="cloudFiles"></param>
631
        /// <param name="pollTime"></param>
632
        private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
633
        {
634
            if (accountInfo == null)
635
                throw new ArgumentNullException("accountInfo");
636
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
637
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
638
            if (cloudFiles == null)
639
                throw new ArgumentNullException("cloudFiles");
640
            Contract.EndContractBlock();
641

    
642
            //Check the Modified date to ensure that were just created and haven't been uploaded yet
643
            //NOTE: The NHibernate LINQ provider doesn't support custom functions so we need to break the query 
644
            //in two steps
645
            //NOTE: DON'T return files that are already in conflict. The first poll would mark them as 
646
            //"In Conflict" but subsequent polls would delete them
647
/*            var t=FileState.Find(new Guid("{cd664c9a-5f17-47c9-b27f-3bcbcb0595ff}"));
648

    
649
            var d0 = FileState.Queryable
650
                .Where(state => 
651
                            state.FilePath.StartsWith(accountInfo.AccountPath)).ToList();
652
            
653
            var d1 = FileState.Queryable
654
                .Where(state => state.Modified <= pollTime).ToList();
655
            var d2= FileState.Queryable
656
                .Where(state => state.Modified <= pollTime
657
                            &&
658
                            state.FilePath.StartsWith(accountInfo.AccountPath)).ToList();*/
659

    
660
            var deleteCandidates = FileState.Queryable
661
                .Where(state => state.Modified <= pollTime
662
                            &&
663
                            state.FilePath.StartsWith(accountInfo.AccountPath)
664
                            && state.FileStatus != FileStatus.Conflict).ToList();
665
/*
666
            var deleteCandidates = (from state in FileState.Queryable
667
                                   where 
668
                                        state.Modified <= pollTime 
669
                                        && state.FilePath.StartsWith(accountInfo.AccountPath)
670
                                        && state.FileStatus != FileStatus.Conflict
671
                                   select state).ToList();
672
*/
673

    
674
            var filesToDelete = (from deleteCandidate in deleteCandidates 
675
                         let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath) 
676
                         let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath) 
677
                         where !cloudFiles.Any(r => Path.Combine(r.Container, r.Name) == relativeFilePath) 
678
                         select localFile).ToList();
679

    
680
            //On the first run
681
            if (_firstPoll)
682
            {
683
                //Set the status of missing files to Conflict
684
                foreach (var item in filesToDelete)
685
                {
686
                    StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);
687
                }
688
                StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted",filesToDelete.Count));
689
            }
690
            else
691
            {
692
                foreach (var item in filesToDelete)
693
                {
694
                    item.Delete();
695
                    StatusKeeper.ClearFileStatus(item.FullName);
696
                }
697
                StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted",filesToDelete.Count),TraceLevel.Info);
698
            }
699

    
700
        }
701

    
702
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
703
        {
704
            var containerPaths = from container in containers
705
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
706
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
707
                                 select containerPath;
708

    
709
            foreach (var path in containerPaths)
710
            {
711
                Directory.CreateDirectory(path);
712
            }
713
        }
714

    
715
        //Creates an appropriate action for each server file
716
        private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
717
        {
718
            if (remote==null)
719
                throw new ArgumentNullException();
720
            Contract.EndContractBlock();
721
            var fileAgent = GetFileAgent(accountInfo);
722

    
723
            //In order to avoid multiple iterations over the files, we iterate only once
724
            //over the remote files
725
            foreach (var objectInfo in remote)
726
            {
727
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
728
                //and remove any matching objects from the list, adding them to the commonObjects list
729
                
730
                if (fileAgent.Exists(relativePath))
731
                {
732
                    //If a directory object already exists, we don't need to perform any other action                    
733
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
734
                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
735
                        continue;
736
                    using (new SessionScope(FlushAction.Never))
737
                    {
738
                        var state =  StatusKeeper.GetStateByFilePath(localFile.FullName);
739
                        //FileState.FindByFilePath(localFile.FullName);
740
                        //Common files should be checked on a per-case basis to detect differences, which is newer
741

    
742
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
743
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
744
                                                     accountInfo.BlockHash);
745
                    }
746
                }
747
                else
748
                {
749
                    //If there is no match we add them to the localFiles list
750
                    //but only if the file is not marked for deletion
751
                    var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
752
                    var fileStatus = StatusKeeper.GetFileStatus(targetFile);
753
                    if (fileStatus != FileStatus.Deleted)
754
                    {
755
                        //Remote files should be downloaded
756
                        yield return new CloudDownloadAction(accountInfo,objectInfo);
757
                    }
758
                }
759
            }            
760
        }
761

    
762
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
763
        {
764
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
765
        }
766

    
767
        private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
768
        {
769
            var fileAgent = GetFileAgent(accountInfo);
770
            foreach (var trashObject in trashObjects)
771
            {
772
                var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
773
                //HACK: Assume only the "pithos" container is used. Must find out what happens when
774
                //deleting a file from a different container
775
                var relativePath = Path.Combine("pithos", barePath);
776
                fileAgent.Delete(relativePath);                                
777
            }
778
        }
779

    
780

    
781
        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
782
        {
783
            if (accountInfo==null)
784
                throw new ArgumentNullException("accountInfo");
785
            if (action==null)
786
                throw new ArgumentNullException("action");
787
            if (action.CloudFile==null)
788
                throw new ArgumentException("CloudFile","action");
789
            if (action.LocalFile==null)
790
                throw new ArgumentException("LocalFile","action");
791
            if (action.OldLocalFile==null)
792
                throw new ArgumentException("OldLocalFile","action");
793
            if (action.OldCloudFile==null)
794
                throw new ArgumentException("OldCloudFile","action");
795
            Contract.EndContractBlock();
796
            
797
            
798
            var newFilePath = action.LocalFile.FullName;
799
            
800
            //How do we handle concurrent renames and deletes/uploads/downloads?
801
            //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
802
            //  This should never happen as the network agent executes only one action at a time
803
            //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
804
            //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
805
            //  same name will fail.
806
            //  This should never happen as the network agent executes only one action at a time.
807
            //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
808
            //  to remove the rename from the queue.
809
            //  We can probably ignore this case. It will result in an error which should be ignored            
810

    
811
            
812
            //The local file is already renamed
813
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
814

    
815

    
816
            var account = action.CloudFile.Account ?? accountInfo.UserName;
817
            var container = action.CloudFile.Container;
818
            
819
            var client = new CloudFilesClient(accountInfo);
820
            //TODO: What code is returned when the source file doesn't exist?
821
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
822

    
823
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
824
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
825
            NativeMethods.RaiseChangeNotification(newFilePath);
826
        }
827

    
828
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
829
        {
830
            if (accountInfo == null)
831
                throw new ArgumentNullException("accountInfo");
832
            if (cloudFile==null)
833
                throw new ArgumentNullException("cloudFile");
834

    
835
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
836
                throw new ArgumentException("Invalid container", "cloudFile");
837
            Contract.EndContractBlock();
838
            
839
            var fileAgent = GetFileAgent(accountInfo);
840

    
841
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
842
            {
843
                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
844
                var info = fileAgent.GetFileSystemInfo(fileName);                
845
                var fullPath = info.FullName.ToLower();
846

    
847
                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
848

    
849
                var account = cloudFile.Account ?? accountInfo.UserName;
850
                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
851

    
852
                var client = new CloudFilesClient(accountInfo);
853
                client.DeleteObject(account, container, cloudFile.Name);
854

    
855
                StatusKeeper.ClearFileStatus(fullPath);
856
            }
857
        }
858

    
859
        //Download a file.
860
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
861
        {
862
            if (accountInfo == null)
863
                throw new ArgumentNullException("accountInfo");
864
            if (cloudFile == null)
865
                throw new ArgumentNullException("cloudFile");
866
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
867
                throw new ArgumentNullException("cloudFile");
868
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
869
                throw new ArgumentNullException("cloudFile");
870
            if (String.IsNullOrWhiteSpace(filePath))
871
                throw new ArgumentNullException("filePath");
872
            if (!Path.IsPathRooted(filePath))
873
                throw new ArgumentException("The filePath must be rooted", "filePath");
874
            Contract.EndContractBlock();
875

    
876
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
877
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
878

    
879
            var url = relativeUrl.ToString();
880
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
881
                return;
882

    
883

    
884
            //Are we already downloading or uploading the file? 
885
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
886
            {
887
                if (gate.Failed)
888
                    return;
889
                //The file's hashmap will be stored in the same location with the extension .hashmap
890
                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
891
                
892
                var client = new CloudFilesClient(accountInfo);
893
                var account = cloudFile.Account;
894
                var container = cloudFile.Container;
895

    
896
                if (cloudFile.Content_Type == @"application/directory")
897
                {
898
                    if (!Directory.Exists(localPath))
899
                        Directory.CreateDirectory(localPath);
900
                }
901
                else
902
                {
903
                    //Retrieve the hashmap from the server
904
                    var serverHash = await client.GetHashMap(account, container, url);
905
                    //If it's a small file
906
                    if (serverHash.Hashes.Count == 1)
907
                        //Download it in one go
908
                        await
909
                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
910
                        //Otherwise download it block by block
911
                    else
912
                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
913

    
914
                    if (cloudFile.AllowedTo == "read")
915
                    {
916
                        var attributes = File.GetAttributes(localPath);
917
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
918
                    }
919
                }
920

    
921
                //Now we can store the object's metadata without worrying about ghost status entries
922
                StatusKeeper.StoreInfo(localPath, cloudFile);
923
                
924
            }
925
        }
926

    
927
        //Download a small file with a single GET operation
928
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
929
        {
930
            if (client == null)
931
                throw new ArgumentNullException("client");
932
            if (cloudFile==null)
933
                throw new ArgumentNullException("cloudFile");
934
            if (relativeUrl == null)
935
                throw new ArgumentNullException("relativeUrl");
936
            if (String.IsNullOrWhiteSpace(filePath))
937
                throw new ArgumentNullException("filePath");
938
            if (!Path.IsPathRooted(filePath))
939
                throw new ArgumentException("The localPath must be rooted", "filePath");
940
            Contract.EndContractBlock();
941

    
942
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
943
            //If the file already exists
944
            if (File.Exists(localPath))
945
            {
946
                //First check with MD5 as this is a small file
947
                var localMD5 = Signature.CalculateMD5(localPath);
948
                var cloudHash=serverHash.TopHash.ToHashString();
949
                if (localMD5==cloudHash)
950
                    return;
951
                //Then check with a treehash
952
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
953
                var localHash = localTreeHash.TopHash.ToHashString();
954
                if (localHash==cloudHash)
955
                    return;
956
            }
957

    
958
            var fileAgent = GetFileAgent(accountInfo);
959
            //Calculate the relative file path for the new file
960
            var relativePath = relativeUrl.RelativeUriToFilePath();
961
            //The file will be stored in a temporary location while downloading with an extension .download
962
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
963
            //Make sure the target folder exists. DownloadFileTask will not create the folder
964
            var tempFolder = Path.GetDirectoryName(tempPath);
965
            if (!Directory.Exists(tempFolder))
966
                Directory.CreateDirectory(tempFolder);
967

    
968
            //Download the object to the temporary location
969
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
970

    
971
            //Create the local folder if it doesn't exist (necessary for shared objects)
972
            var localFolder = Path.GetDirectoryName(localPath);
973
            if (!Directory.Exists(localFolder))
974
                Directory.CreateDirectory(localFolder);            
975
            //And move it to its actual location once downloading is finished
976
            if (File.Exists(localPath))
977
                File.Replace(tempPath,localPath,null,true);
978
            else
979
                File.Move(tempPath,localPath);
980
            //Notify listeners that a local file has changed
981
            StatusNotification.NotifyChangedFile(localPath);
982

    
983
                       
984
        }
985

    
986
        //Download a file asynchronously using blocks
987
        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
988
        {
989
            if (client == null)
990
                throw new ArgumentNullException("client");
991
            if (cloudFile == null)
992
                throw new ArgumentNullException("cloudFile");
993
            if (relativeUrl == null)
994
                throw new ArgumentNullException("relativeUrl");
995
            if (String.IsNullOrWhiteSpace(filePath))
996
                throw new ArgumentNullException("filePath");
997
            if (!Path.IsPathRooted(filePath))
998
                throw new ArgumentException("The filePath must be rooted", "filePath");
999
            if (serverHash == null)
1000
                throw new ArgumentNullException("serverHash");
1001
            Contract.EndContractBlock();
1002
            
1003
           var fileAgent = GetFileAgent(accountInfo);
1004
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
1005
            
1006
            //Calculate the relative file path for the new file
1007
            var relativePath = relativeUrl.RelativeUriToFilePath();
1008
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
1009

    
1010
            
1011
                        
1012
            //Calculate the file's treehash
1013
            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
1014
                
1015
            //And compare it with the server's hash
1016
            var upHashes = serverHash.GetHashesAsStrings();
1017
            var localHashes = treeHash.HashDictionary;
1018
            for (int i = 0; i < upHashes.Length; i++)
1019
            {
1020
                //For every non-matching hash
1021
                var upHash = upHashes[i];
1022
                if (!localHashes.ContainsKey(upHash))
1023
                {
1024
                    if (blockUpdater.UseOrphan(i, upHash))
1025
                    {
1026
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
1027
                        continue;
1028
                    }
1029
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
1030
                    var start = i*serverHash.BlockSize;
1031
                    //To download the last block just pass a null for the end of the range
1032
                    long? end = null;
1033
                    if (i < upHashes.Length - 1 )
1034
                        end= ((i + 1)*serverHash.BlockSize) ;
1035
                            
1036
                    //Download the missing block
1037
                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
1038

    
1039
                    //and store it
1040
                    blockUpdater.StoreBlock(i, block);
1041

    
1042

    
1043
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
1044
                }
1045
            }
1046

    
1047
            //Want to avoid notifications if no changes were made
1048
            var hasChanges = blockUpdater.HasBlocks;
1049
            blockUpdater.Commit();
1050
            
1051
            if (hasChanges)
1052
                //Notify listeners that a local file has changed
1053
                StatusNotification.NotifyChangedFile(localPath);
1054

    
1055
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
1056
        }
1057

    
1058

    
1059
        private async Task UploadCloudFile(CloudAction action)
1060
        {
1061
            if (action == null)
1062
                throw new ArgumentNullException("action");           
1063
            Contract.EndContractBlock();
1064

    
1065
            try
1066
            {
1067
                var accountInfo = action.AccountInfo;
1068

    
1069
                var fileInfo = action.LocalFile;
1070

    
1071
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
1072
                    return;
1073
                
1074
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
1075
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
1076
                {
1077
                    var parts = relativePath.Split('\\');
1078
                    var accountName = parts[1];
1079
                    var oldName = accountInfo.UserName;
1080
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
1081
                    var nameIndex = absoluteUri.IndexOf(oldName);
1082
                    var root = absoluteUri.Substring(0, nameIndex);
1083

    
1084
                    accountInfo = new AccountInfo
1085
                    {
1086
                        UserName = accountName,
1087
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
1088
                        StorageUri = new Uri(root + accountName),
1089
                        BlockHash = accountInfo.BlockHash,
1090
                        BlockSize = accountInfo.BlockSize,
1091
                        Token = accountInfo.Token
1092
                    };
1093
                }
1094

    
1095

    
1096
                var fullFileName = fileInfo.GetProperCapitalization();
1097
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
1098
                {
1099
                    //Abort if the file is already being uploaded or downloaded
1100
                    if (gate.Failed)
1101
                        return;
1102

    
1103
                    var cloudFile = action.CloudFile;
1104
                    var account = cloudFile.Account ?? accountInfo.UserName;
1105

    
1106
                    var client = new CloudFilesClient(accountInfo);                    
1107
                    //Even if GetObjectInfo times out, we can proceed with the upload            
1108
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
1109

    
1110
                    //If this is a read-only file, do not upload changes
1111
                    if (info.AllowedTo == "read")
1112
                        return;
1113
                    
1114
                    //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
1115
                    if (fileInfo is DirectoryInfo)
1116
                    {
1117
                        //If the directory doesn't exist the Hash property will be empty
1118
                        if (String.IsNullOrWhiteSpace(info.Hash))
1119
                            //Go on and create the directory
1120
                            await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
1121
                    }
1122
                    else
1123
                    {
1124

    
1125
                        var cloudHash = info.Hash.ToLower();
1126

    
1127
                        var hash = action.LocalHash.Value;
1128
                        var topHash = action.TopHash.Value;
1129

    
1130
                        //If the file hashes match, abort the upload
1131
                        if (hash == cloudHash || topHash == cloudHash)
1132
                        {
1133
                            //but store any metadata changes 
1134
                            StatusKeeper.StoreInfo(fullFileName, info);
1135
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1136
                            return;
1137
                        }
1138

    
1139

    
1140
                        //Mark the file as modified while we upload it
1141
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1142
                        //And then upload it
1143

    
1144
                        //Upload even small files using the Hashmap. The server may already contain
1145
                        //the relevant block
1146

    
1147
                        //First, calculate the tree hash
1148
                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1149
                                                                              accountInfo.BlockHash);
1150

    
1151
                        await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1152
                    }
1153
                    //If everything succeeds, change the file and overlay status to normal
1154
                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1155
                }
1156
                //Notify the Shell to update the overlays
1157
                NativeMethods.RaiseChangeNotification(fullFileName);
1158
                StatusNotification.NotifyChangedFile(fullFileName);
1159
            }
1160
            catch (AggregateException ex)
1161
            {
1162
                var exc = ex.InnerException as WebException;
1163
                if (exc == null)
1164
                    throw ex.InnerException;
1165
                if (HandleUploadWebException(action, exc)) 
1166
                    return;
1167
                throw;
1168
            }
1169
            catch (WebException ex)
1170
            {
1171
                if (HandleUploadWebException(action, ex))
1172
                    return;
1173
                throw;
1174
            }
1175
            catch (Exception ex)
1176
            {
1177
                Log.Error("Unexpected error while uploading file", ex);
1178
                throw;
1179
            }
1180

    
1181
        }
1182

    
1183
        private bool IsDeletedFile(CloudAction action)
1184
        {            
1185
            var key = GetFileKey(action.CloudFile);
1186
            DateTime entryDate;
1187
            if (_deletedFiles.TryGetValue(key, out entryDate))
1188
            {
1189
                //If the delete entry was created after this action, abort the action
1190
                if (entryDate > action.Created)
1191
                    return true;
1192
                //Otherwise, remove the stale entry 
1193
                _deletedFiles.TryRemove(key, out entryDate);
1194
            }
1195
            return false;
1196
        }
1197

    
1198
        private bool HandleUploadWebException(CloudAction action, WebException exc)
1199
        {
1200
            var response = exc.Response as HttpWebResponse;
1201
            if (response == null)
1202
                throw exc;
1203
            if (response.StatusCode == HttpStatusCode.Unauthorized)
1204
            {
1205
                Log.Error("Not allowed to upload file", exc);
1206
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1207
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1208
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
1209
                return true;
1210
            }
1211
            return false;
1212
        }
1213

    
1214
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1215
        {
1216
            if (accountInfo == null)
1217
                throw new ArgumentNullException("accountInfo");
1218
            if (cloudFile==null)
1219
                throw new ArgumentNullException("cloudFile");
1220
            if (fileInfo == null)
1221
                throw new ArgumentNullException("fileInfo");
1222
            if (String.IsNullOrWhiteSpace(url))
1223
                throw new ArgumentNullException(url);
1224
            if (treeHash==null)
1225
                throw new ArgumentNullException("treeHash");
1226
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1227
                throw new ArgumentException("Invalid container","cloudFile");
1228
            Contract.EndContractBlock();
1229

    
1230
            var fullFileName = fileInfo.GetProperCapitalization();
1231

    
1232
            var account = cloudFile.Account ?? accountInfo.UserName;
1233
            var container = cloudFile.Container ;
1234

    
1235
            var client = new CloudFilesClient(accountInfo);
1236
            //Send the hashmap to the server            
1237
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
1238
            //If the server returns no missing hashes, we are done
1239
            while (missingHashes.Count > 0)
1240
            {
1241

    
1242
                var buffer = new byte[accountInfo.BlockSize];
1243
                foreach (var missingHash in missingHashes)
1244
                {
1245
                    //Find the proper block
1246
                    var blockIndex = treeHash.HashDictionary[missingHash];
1247
                    var offset = blockIndex*accountInfo.BlockSize;
1248

    
1249
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1250

    
1251
                    try
1252
                    {
1253
                        //And upload the block                
1254
                        await client.PostBlock(account, container, buffer, 0, read);
1255
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1256
                    }
1257
                    catch (Exception exc)
1258
                    {
1259
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1260
                    }
1261

    
1262
                }
1263

    
1264
                //Repeat until there are no more missing hashes                
1265
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
1266
            }
1267
        }
1268

    
1269

    
1270
        public void AddAccount(AccountInfo accountInfo)
1271
        {            
1272
            if (!_accounts.Contains(accountInfo))
1273
                _accounts.Add(accountInfo);
1274
        }
1275
    }
1276

    
1277
   
1278

    
1279

    
1280
}