Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ add4f744

History | View | Annotate | Download (59.7 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
            StatusKeeper.SetPithosStatus(PithosStatus.Syncing);
124
            var accountInfo = action.AccountInfo;
125

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

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

    
133
                try
134
                {
135

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

    
204
                    _agent.Post(action);
205
                }
206
                finally
207
                {
208
                    StatusKeeper.SetPithosStatus(PithosStatus.InSynch);
209
                }
210
            }
211
        }
212

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

    
233
            var accountInfo = action.AccountInfo;
234

    
235
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
236
            {                
237
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
238

    
239
                var cloudFile = action.CloudFile;
240

    
241
                try
242
                {
243
                    //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
244
                    //agent
245
                    using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
246
                    {
247

    
248
                        //Add the file URL to the deleted files list
249
                        var key = GetFileKey(action.CloudFile);
250
                        _deletedFiles[key] = DateTime.Now;
251

    
252
                        _pauseAgent.Reset();
253
                        // and then delete the file from the server
254
                        DeleteCloudFile(accountInfo, cloudFile);
255

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

    
287
                    _deleteAgent.Post(action);
288
                }
289
                finally
290
                {
291
                    if (_deleteAgent.InputCount == 0)
292
                        _pauseAgent.Set();
293

    
294
                }
295
            }
296
        }
297

    
298
        private static string GetFileKey(ObjectInfo info)
299
        {
300
            var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
301
            return key;
302
        }
303

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

    
318
            var localFile = action.LocalFile;
319
            var cloudFile = action.CloudFile;
320
            var downloadPath=action.LocalFile.GetProperCapitalization();
321

    
322
            var cloudHash = cloudFile.Hash.ToLower();
323
            var localHash = action.LocalHash.Value.ToLower();
324
            var topHash = action.TopHash.Value.ToLower();
325

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

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

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

    
377
        private void ReportConflict(string downloadPath)
378
        {
379
            if (String.IsNullOrWhiteSpace(downloadPath))
380
                throw new ArgumentNullException("downloadPath");
381
            Contract.EndContractBlock();
382

    
383
            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
384
            StatusKeeper.SetPithosStatus(PithosStatus.HasConflicts);
385
            var message = String.Format("Conflict detected for file {0}", downloadPath);
386
            Log.Warn(message);
387
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
388
        }
389

    
390
        public void Post(CloudAction cloudAction)
391
        {
392
            if (cloudAction == null)
393
                throw new ArgumentNullException("cloudAction");
394
            if (cloudAction.AccountInfo==null)
395
                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
396
            Contract.EndContractBlock();
397

    
398
            _pauseAgent.Wait();
399

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

    
428
       /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
429
        {
430
            public bool Equals(ObjectInfo x, ObjectInfo y)
431
            {
432
                return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
433
            }
434

    
435
            public int GetHashCode(ObjectInfo obj)
436
            {
437
                return obj.Name.ToLower().GetHashCode();
438
            }
439
        }*/
440

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

    
453
        //Remote files are polled periodically. Any changes are processed
454
        public async Task PollRemoteFiles(DateTime? since = null,bool repeat=true)
455
        {
456
            StatusNotification.Notify(new Notification{Title="Polling Pithos"});
457
            StatusKeeper.SetPithosStatus(PithosStatus.Syncing);
458

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

    
469
                    var tasks = from accountInfo in _accounts
470
                                select ProcessAccountFiles(accountInfo, since);
471

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

    
487
                //Wait for the polling interval to pass or the Manual flat to be toggled
488
                nextSince = await WaitForScheduledOrManualPoll(nextSince);
489

    
490
                PollRemoteFiles(nextSince);
491

    
492
            }
493
        }
494

    
495
        private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
496
        {            
497
            _tcs = new TaskCompletionSource<bool>();
498
            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
499
            var signaledTask = await TaskEx.WhenAny(_tcs.Task, wait);
500
            //If polling is signalled by SynchNow, ignore the since tag
501
            if (signaledTask is Task<bool>)
502
                return null;
503
            return since;
504
        }
505

    
506
        public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
507
        {   
508
            if (accountInfo==null)
509
                throw new ArgumentNullException("accountInfo");
510
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
511
                throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
512
            Contract.EndContractBlock();
513

    
514
            StatusNotification.Notify(new Notification{Title=String.Format("Polling {0}",accountInfo.UserName)});
515

    
516
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
517
            {
518
                Log.Info("Scheduled");
519
                var client=new CloudFilesClient(accountInfo);
520

    
521
                var containers = client.ListContainers(accountInfo.UserName);
522
                
523
                CreateContainerFolders(accountInfo, containers);
524

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

    
538
                    var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => client.ListSharedObjects(since), "shared");
539
                    listObjects.Add(listShared);
540
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
541

    
542
                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
543
                    {
544
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
545

    
546
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
547
                        var remoteObjects = from objectList in listTasks
548
                                            where (string) objectList.AsyncState != "trash"
549
                                            from obj in objectList.Result
550
                                            select obj;
551

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

    
580
                        var trashObjects = dict["trash"].Result;
581
                        var sharedObjects = dict["shared"].Result;
582

    
583
                        //Items with the same name, hash may be both in the container and the trash
584
                        //Don't delete items that exist in the container
585
                        var realTrash = from trash in trashObjects
586
                                        where
587
                                            !remoteObjects.Any(
588
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
589
                                        select trash;
590
                        ProcessTrashedFiles(accountInfo, realTrash);
591

    
592

    
593
                        var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
594
                                     let name = info.Name
595
                                     where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
596
                                           !name.StartsWith(FolderConstants.CacheFolder + "/",
597
                                                            StringComparison.InvariantCultureIgnoreCase)
598
                                     select info).ToList();
599

    
600

    
601

    
602
                        ProcessDeletedFiles(accountInfo, cleanRemotes, pollTime);
603

    
604
                        //Create a list of actions from the remote files
605
                        var allActions = ObjectsToActions(accountInfo, cleanRemotes);
606

    
607
                        
608
                        //var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
609

    
610
                        //And remove those that are already being processed by the agent
611
                        var distinctActions = allActions
612
                            .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
613
                            .ToList();
614

    
615
                        if (distinctActions.Any())
616
                        {
617
                            StatusNotification.Notify(new Notification {Title = "Changes Detected",Message=String.Format("{0} files were modified",distinctActions.Count)});
618
                        }
619
                        //Queue all the actions
620
                        foreach (var message in distinctActions)
621
                        {
622
                            Post(message);
623
                        }
624

    
625
                        Log.Info("[LISTENER] End Processing");
626
                    }
627
                }
628
                catch (Exception ex)
629
                {
630
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
631
                    return;
632
                }
633

    
634
                Log.Info("[LISTENER] Finished");
635

    
636
            }
637
        }
638

    
639
        /// <summary>
640
        /// Deletes local files that are not found in the list of cloud files
641
        /// </summary>
642
        /// <param name="accountInfo"></param>
643
        /// <param name="cloudFiles"></param>
644
        /// <param name="pollTime"></param>
645
        private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
646
        {
647
            if (accountInfo == null)
648
                throw new ArgumentNullException("accountInfo");
649
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
650
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
651
            if (cloudFiles == null)
652
                throw new ArgumentNullException("cloudFiles");
653
            Contract.EndContractBlock();
654

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

    
662
            var d0 = FileState.Queryable
663
                .Where(state => 
664
                            state.FilePath.StartsWith(accountInfo.AccountPath)).ToList();
665
            
666
            var d1 = FileState.Queryable
667
                .Where(state => state.Modified <= pollTime).ToList();
668
            var d2= FileState.Queryable
669
                .Where(state => state.Modified <= pollTime
670
                            &&
671
                            state.FilePath.StartsWith(accountInfo.AccountPath)).ToList();*/
672

    
673
            var deleteCandidates = FileState.Queryable
674
                .Where(state => state.Modified <= pollTime
675
                            &&
676
                            state.FilePath.StartsWith(accountInfo.AccountPath)
677
                            && state.FileStatus != FileStatus.Conflict).ToList();
678
/*
679
            var deleteCandidates = (from state in FileState.Queryable
680
                                   where 
681
                                        state.Modified <= pollTime 
682
                                        && state.FilePath.StartsWith(accountInfo.AccountPath)
683
                                        && state.FileStatus != FileStatus.Conflict
684
                                   select state).ToList();
685
*/
686

    
687
            var filesToDelete = (from deleteCandidate in deleteCandidates 
688
                         let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath) 
689
                         let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath) 
690
                         where !cloudFiles.Any(r => Path.Combine(r.Container, r.Name) == relativeFilePath) 
691
                         select localFile).ToList();
692

    
693
            //On the first run
694
            if (_firstPoll)
695
            {
696
                //Set the status of missing files to Conflict
697
                foreach (var item in filesToDelete)
698
                {
699
                    StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);
700
                }
701
                StatusKeeper.SetPithosStatus(PithosStatus.HasConflicts);
702
                StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted",filesToDelete.Count));
703
            }
704
            else
705
            {
706
                foreach (var item in filesToDelete)
707
                {
708
                    item.Delete();
709
                    StatusKeeper.ClearFileStatus(item.FullName);
710
                }
711
                StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted",filesToDelete.Count),TraceLevel.Info);
712
            }
713

    
714
        }
715

    
716
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
717
        {
718
            var containerPaths = from container in containers
719
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
720
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
721
                                 select containerPath;
722

    
723
            foreach (var path in containerPaths)
724
            {
725
                Directory.CreateDirectory(path);
726
            }
727
        }
728

    
729
        //Creates an appropriate action for each server file
730
        private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
731
        {
732
            if (remote==null)
733
                throw new ArgumentNullException();
734
            Contract.EndContractBlock();
735
            var fileAgent = GetFileAgent(accountInfo);
736

    
737
            //In order to avoid multiple iterations over the files, we iterate only once
738
            //over the remote files
739
            foreach (var objectInfo in remote)
740
            {
741
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
742
                //and remove any matching objects from the list, adding them to the commonObjects list
743
                
744
                if (fileAgent.Exists(relativePath))
745
                {
746
                    //If a directory object already exists, we don't need to perform any other action                    
747
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
748
                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
749
                        continue;
750
                    using (new SessionScope(FlushAction.Never))
751
                    {
752
                        var state =  StatusKeeper.GetStateByFilePath(localFile.FullName);
753
                        //FileState.FindByFilePath(localFile.FullName);
754
                        //Common files should be checked on a per-case basis to detect differences, which is newer
755

    
756
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
757
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
758
                                                     accountInfo.BlockHash);
759
                    }
760
                }
761
                else
762
                {
763
                    //If there is no match we add them to the localFiles list
764
                    //but only if the file is not marked for deletion
765
                    var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
766
                    var fileStatus = StatusKeeper.GetFileStatus(targetFile);
767
                    if (fileStatus != FileStatus.Deleted)
768
                    {
769
                        //Remote files should be downloaded
770
                        yield return new CloudDownloadAction(accountInfo,objectInfo);
771
                    }
772
                }
773
            }            
774
        }
775

    
776
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
777
        {
778
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
779
        }
780

    
781
        private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
782
        {
783
            var fileAgent = GetFileAgent(accountInfo);
784
            foreach (var trashObject in trashObjects)
785
            {
786
                var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
787
                //HACK: Assume only the "pithos" container is used. Must find out what happens when
788
                //deleting a file from a different container
789
                var relativePath = Path.Combine("pithos", barePath);
790
                fileAgent.Delete(relativePath);                                
791
            }
792
        }
793

    
794

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

    
825
            
826
            //The local file is already renamed
827
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
828

    
829

    
830
            var account = action.CloudFile.Account ?? accountInfo.UserName;
831
            var container = action.CloudFile.Container;
832
            
833
            var client = new CloudFilesClient(accountInfo);
834
            //TODO: What code is returned when the source file doesn't exist?
835
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
836

    
837
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
838
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
839
            NativeMethods.RaiseChangeNotification(newFilePath);
840
        }
841

    
842
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
843
        {
844
            if (accountInfo == null)
845
                throw new ArgumentNullException("accountInfo");
846
            if (cloudFile==null)
847
                throw new ArgumentNullException("cloudFile");
848

    
849
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
850
                throw new ArgumentException("Invalid container", "cloudFile");
851
            Contract.EndContractBlock();
852
            
853
            var fileAgent = GetFileAgent(accountInfo);
854

    
855
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
856
            {
857
                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
858
                var info = fileAgent.GetFileSystemInfo(fileName);                
859
                var fullPath = info.FullName.ToLower();
860

    
861
                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
862

    
863
                var account = cloudFile.Account ?? accountInfo.UserName;
864
                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
865

    
866
                var client = new CloudFilesClient(accountInfo);
867
                client.DeleteObject(account, container, cloudFile.Name);
868

    
869
                StatusKeeper.ClearFileStatus(fullPath);
870
            }
871
        }
872

    
873
        //Download a file.
874
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
875
        {
876
            if (accountInfo == null)
877
                throw new ArgumentNullException("accountInfo");
878
            if (cloudFile == null)
879
                throw new ArgumentNullException("cloudFile");
880
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
881
                throw new ArgumentNullException("cloudFile");
882
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
883
                throw new ArgumentNullException("cloudFile");
884
            if (String.IsNullOrWhiteSpace(filePath))
885
                throw new ArgumentNullException("filePath");
886
            if (!Path.IsPathRooted(filePath))
887
                throw new ArgumentException("The filePath must be rooted", "filePath");
888
            Contract.EndContractBlock();
889

    
890
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
891
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
892

    
893
            var url = relativeUrl.ToString();
894
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
895
                return;
896

    
897

    
898
            //Are we already downloading or uploading the file? 
899
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
900
            {
901
                if (gate.Failed)
902
                    return;
903
                //The file's hashmap will be stored in the same location with the extension .hashmap
904
                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
905
                
906
                var client = new CloudFilesClient(accountInfo);
907
                var account = cloudFile.Account;
908
                var container = cloudFile.Container;
909

    
910
                if (cloudFile.Content_Type == @"application/directory")
911
                {
912
                    if (!Directory.Exists(localPath))
913
                        Directory.CreateDirectory(localPath);
914
                }
915
                else
916
                {
917
                    //Retrieve the hashmap from the server
918
                    var serverHash = await client.GetHashMap(account, container, url);
919
                    //If it's a small file
920
                    if (serverHash.Hashes.Count == 1)
921
                        //Download it in one go
922
                        await
923
                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
924
                        //Otherwise download it block by block
925
                    else
926
                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
927

    
928
                    if (cloudFile.AllowedTo == "read")
929
                    {
930
                        var attributes = File.GetAttributes(localPath);
931
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
932
                    }
933
                }
934

    
935
                //Now we can store the object's metadata without worrying about ghost status entries
936
                StatusKeeper.StoreInfo(localPath, cloudFile);
937
                
938
            }
939
        }
940

    
941
        //Download a small file with a single GET operation
942
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
943
        {
944
            if (client == null)
945
                throw new ArgumentNullException("client");
946
            if (cloudFile==null)
947
                throw new ArgumentNullException("cloudFile");
948
            if (relativeUrl == null)
949
                throw new ArgumentNullException("relativeUrl");
950
            if (String.IsNullOrWhiteSpace(filePath))
951
                throw new ArgumentNullException("filePath");
952
            if (!Path.IsPathRooted(filePath))
953
                throw new ArgumentException("The localPath must be rooted", "filePath");
954
            Contract.EndContractBlock();
955

    
956
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
957
            //If the file already exists
958
            if (File.Exists(localPath))
959
            {
960
                //First check with MD5 as this is a small file
961
                var localMD5 = Signature.CalculateMD5(localPath);
962
                var cloudHash=serverHash.TopHash.ToHashString();
963
                if (localMD5==cloudHash)
964
                    return;
965
                //Then check with a treehash
966
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
967
                var localHash = localTreeHash.TopHash.ToHashString();
968
                if (localHash==cloudHash)
969
                    return;
970
            }
971

    
972
            var fileAgent = GetFileAgent(accountInfo);
973
            //Calculate the relative file path for the new file
974
            var relativePath = relativeUrl.RelativeUriToFilePath();
975
            //The file will be stored in a temporary location while downloading with an extension .download
976
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
977
            //Make sure the target folder exists. DownloadFileTask will not create the folder
978
            var tempFolder = Path.GetDirectoryName(tempPath);
979
            if (!Directory.Exists(tempFolder))
980
                Directory.CreateDirectory(tempFolder);
981

    
982
            //Download the object to the temporary location
983
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
984

    
985
            //Create the local folder if it doesn't exist (necessary for shared objects)
986
            var localFolder = Path.GetDirectoryName(localPath);
987
            if (!Directory.Exists(localFolder))
988
                Directory.CreateDirectory(localFolder);            
989
            //And move it to its actual location once downloading is finished
990
            if (File.Exists(localPath))
991
                File.Replace(tempPath,localPath,null,true);
992
            else
993
                File.Move(tempPath,localPath);
994
            //Notify listeners that a local file has changed
995
            StatusNotification.NotifyChangedFile(localPath);
996

    
997
                       
998
        }
999

    
1000
        //Download a file asynchronously using blocks
1001
        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
1002
        {
1003
            if (client == null)
1004
                throw new ArgumentNullException("client");
1005
            if (cloudFile == null)
1006
                throw new ArgumentNullException("cloudFile");
1007
            if (relativeUrl == null)
1008
                throw new ArgumentNullException("relativeUrl");
1009
            if (String.IsNullOrWhiteSpace(filePath))
1010
                throw new ArgumentNullException("filePath");
1011
            if (!Path.IsPathRooted(filePath))
1012
                throw new ArgumentException("The filePath must be rooted", "filePath");
1013
            if (serverHash == null)
1014
                throw new ArgumentNullException("serverHash");
1015
            Contract.EndContractBlock();
1016
            
1017
           var fileAgent = GetFileAgent(accountInfo);
1018
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
1019
            
1020
            //Calculate the relative file path for the new file
1021
            var relativePath = relativeUrl.RelativeUriToFilePath();
1022
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
1023

    
1024
            
1025
                        
1026
            //Calculate the file's treehash
1027
            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
1028
                
1029
            //And compare it with the server's hash
1030
            var upHashes = serverHash.GetHashesAsStrings();
1031
            var localHashes = treeHash.HashDictionary;
1032
            for (int i = 0; i < upHashes.Length; i++)
1033
            {
1034
                //For every non-matching hash
1035
                var upHash = upHashes[i];
1036
                if (!localHashes.ContainsKey(upHash))
1037
                {
1038
                    if (blockUpdater.UseOrphan(i, upHash))
1039
                    {
1040
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
1041
                        continue;
1042
                    }
1043
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
1044
                    var start = i*serverHash.BlockSize;
1045
                    //To download the last block just pass a null for the end of the range
1046
                    long? end = null;
1047
                    if (i < upHashes.Length - 1 )
1048
                        end= ((i + 1)*serverHash.BlockSize) ;
1049
                            
1050
                    //Download the missing block
1051
                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
1052

    
1053
                    //and store it
1054
                    blockUpdater.StoreBlock(i, block);
1055

    
1056

    
1057
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
1058
                }
1059
            }
1060

    
1061
            //Want to avoid notifications if no changes were made
1062
            var hasChanges = blockUpdater.HasBlocks;
1063
            blockUpdater.Commit();
1064
            
1065
            if (hasChanges)
1066
                //Notify listeners that a local file has changed
1067
                StatusNotification.NotifyChangedFile(localPath);
1068

    
1069
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
1070
        }
1071

    
1072

    
1073
        private async Task UploadCloudFile(CloudAction action)
1074
        {
1075
            if (action == null)
1076
                throw new ArgumentNullException("action");           
1077
            Contract.EndContractBlock();
1078

    
1079
            try
1080
            {
1081
                var accountInfo = action.AccountInfo;
1082

    
1083
                var fileInfo = action.LocalFile;
1084

    
1085
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
1086
                    return;
1087
                
1088
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
1089
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
1090
                {
1091
                    var parts = relativePath.Split('\\');
1092
                    var accountName = parts[1];
1093
                    var oldName = accountInfo.UserName;
1094
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
1095
                    var nameIndex = absoluteUri.IndexOf(oldName);
1096
                    var root = absoluteUri.Substring(0, nameIndex);
1097

    
1098
                    accountInfo = new AccountInfo
1099
                    {
1100
                        UserName = accountName,
1101
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
1102
                        StorageUri = new Uri(root + accountName),
1103
                        BlockHash = accountInfo.BlockHash,
1104
                        BlockSize = accountInfo.BlockSize,
1105
                        Token = accountInfo.Token
1106
                    };
1107
                }
1108

    
1109

    
1110
                var fullFileName = fileInfo.GetProperCapitalization();
1111
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
1112
                {
1113
                    //Abort if the file is already being uploaded or downloaded
1114
                    if (gate.Failed)
1115
                        return;
1116

    
1117
                    var cloudFile = action.CloudFile;
1118
                    var account = cloudFile.Account ?? accountInfo.UserName;
1119

    
1120
                    var client = new CloudFilesClient(accountInfo);                    
1121
                    //Even if GetObjectInfo times out, we can proceed with the upload            
1122
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
1123

    
1124
                    //If this is a read-only file, do not upload changes
1125
                    if (info.AllowedTo == "read")
1126
                        return;
1127
                    
1128
                    //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
1129
                    if (fileInfo is DirectoryInfo)
1130
                    {
1131
                        //If the directory doesn't exist the Hash property will be empty
1132
                        if (String.IsNullOrWhiteSpace(info.Hash))
1133
                            //Go on and create the directory
1134
                            await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
1135
                    }
1136
                    else
1137
                    {
1138

    
1139
                        var cloudHash = info.Hash.ToLower();
1140

    
1141
                        var hash = action.LocalHash.Value;
1142
                        var topHash = action.TopHash.Value;
1143

    
1144
                        //If the file hashes match, abort the upload
1145
                        if (hash == cloudHash || topHash == cloudHash)
1146
                        {
1147
                            //but store any metadata changes 
1148
                            StatusKeeper.StoreInfo(fullFileName, info);
1149
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1150
                            return;
1151
                        }
1152

    
1153

    
1154
                        //Mark the file as modified while we upload it
1155
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1156
                        //And then upload it
1157

    
1158
                        //Upload even small files using the Hashmap. The server may already contain
1159
                        //the relevant block
1160

    
1161
                        //First, calculate the tree hash
1162
                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1163
                                                                              accountInfo.BlockHash);
1164

    
1165
                        await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1166
                    }
1167
                    //If everything succeeds, change the file and overlay status to normal
1168
                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1169
                }
1170
                //Notify the Shell to update the overlays
1171
                NativeMethods.RaiseChangeNotification(fullFileName);
1172
                StatusNotification.NotifyChangedFile(fullFileName);
1173
            }
1174
            catch (AggregateException ex)
1175
            {
1176
                var exc = ex.InnerException as WebException;
1177
                if (exc == null)
1178
                    throw ex.InnerException;
1179
                if (HandleUploadWebException(action, exc)) 
1180
                    return;
1181
                throw;
1182
            }
1183
            catch (WebException ex)
1184
            {
1185
                if (HandleUploadWebException(action, ex))
1186
                    return;
1187
                throw;
1188
            }
1189
            catch (Exception ex)
1190
            {
1191
                Log.Error("Unexpected error while uploading file", ex);
1192
                throw;
1193
            }
1194

    
1195
        }
1196

    
1197
        private bool IsDeletedFile(CloudAction action)
1198
        {            
1199
            var key = GetFileKey(action.CloudFile);
1200
            DateTime entryDate;
1201
            if (_deletedFiles.TryGetValue(key, out entryDate))
1202
            {
1203
                //If the delete entry was created after this action, abort the action
1204
                if (entryDate > action.Created)
1205
                    return true;
1206
                //Otherwise, remove the stale entry 
1207
                _deletedFiles.TryRemove(key, out entryDate);
1208
            }
1209
            return false;
1210
        }
1211

    
1212
        private bool HandleUploadWebException(CloudAction action, WebException exc)
1213
        {
1214
            var response = exc.Response as HttpWebResponse;
1215
            if (response == null)
1216
                throw exc;
1217
            if (response.StatusCode == HttpStatusCode.Unauthorized)
1218
            {
1219
                Log.Error("Not allowed to upload file", exc);
1220
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1221
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1222
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
1223
                return true;
1224
            }
1225
            return false;
1226
        }
1227

    
1228
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1229
        {
1230
            if (accountInfo == null)
1231
                throw new ArgumentNullException("accountInfo");
1232
            if (cloudFile==null)
1233
                throw new ArgumentNullException("cloudFile");
1234
            if (fileInfo == null)
1235
                throw new ArgumentNullException("fileInfo");
1236
            if (String.IsNullOrWhiteSpace(url))
1237
                throw new ArgumentNullException(url);
1238
            if (treeHash==null)
1239
                throw new ArgumentNullException("treeHash");
1240
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1241
                throw new ArgumentException("Invalid container","cloudFile");
1242
            Contract.EndContractBlock();
1243

    
1244
            var fullFileName = fileInfo.GetProperCapitalization();
1245

    
1246
            var account = cloudFile.Account ?? accountInfo.UserName;
1247
            var container = cloudFile.Container ;
1248

    
1249
            var client = new CloudFilesClient(accountInfo);
1250
            //Send the hashmap to the server            
1251
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
1252
            //If the server returns no missing hashes, we are done
1253
            while (missingHashes.Count > 0)
1254
            {
1255

    
1256
                var buffer = new byte[accountInfo.BlockSize];
1257
                foreach (var missingHash in missingHashes)
1258
                {
1259
                    //Find the proper block
1260
                    var blockIndex = treeHash.HashDictionary[missingHash];
1261
                    var offset = blockIndex*accountInfo.BlockSize;
1262

    
1263
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1264

    
1265
                    try
1266
                    {
1267
                        //And upload the block                
1268
                        await client.PostBlock(account, container, buffer, 0, read);
1269
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1270
                    }
1271
                    catch (Exception exc)
1272
                    {
1273
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1274
                    }
1275

    
1276
                }
1277

    
1278
                //Repeat until there are no more missing hashes                
1279
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
1280
            }
1281
        }
1282

    
1283

    
1284
        public void AddAccount(AccountInfo accountInfo)
1285
        {            
1286
            if (!_accounts.Contains(accountInfo))
1287
                _accounts.Add(accountInfo);
1288
        }
1289
    }
1290

    
1291
   
1292

    
1293

    
1294
}