Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 2edb4807

History | View | Annotate | Download (62.2 kB)

1
// -----------------------------------------------------------------------
2
// <copyright file="NetworkAgent.cs" company="GRNET">
3
// Copyright 2011-2012 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
        private ConcurrentDictionary<string,DateTime> _lastSeen=new ConcurrentDictionary<string, DateTime>();
85

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

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

    
114
        }
115

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

    
124
            UpdateStatus(PithosStatus.Syncing);
125
            var accountInfo = action.AccountInfo;
126

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

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

    
134
                try
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
                    UpdateStatus(PithosStatus.InSynch);                    
209
                }
210
            }
211
        }
212

    
213
        private void UpdateStatus(PithosStatus status)
214
        {
215
            StatusKeeper.SetPithosStatus(status);
216
            StatusNotification.Notify(new Notification());
217
        }
218

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

    
239
            var accountInfo = action.AccountInfo;
240

    
241
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
242
            {                
243
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
244

    
245
                var cloudFile = action.CloudFile;
246

    
247
                try
248
                {
249
                    //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
250
                    //agent
251
                    using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
252
                    {
253

    
254
                        //Add the file URL to the deleted files list
255
                        var key = GetFileKey(action.CloudFile);
256
                        _deletedFiles[key] = DateTime.Now;
257

    
258
                        _pauseAgent.Reset();
259
                        // and then delete the file from the server
260
                                DeleteCloudFile(accountInfo, cloudFile);
261

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

    
293
                    _deleteAgent.Post(action);
294
                }
295
                finally
296
                {
297
                    //Set the event when all delete actions are processed
298
                    if (_deleteAgent.InputCount == 0)
299
                        _pauseAgent.Set();
300

    
301
                }
302
            }
303
        }
304

    
305
        private static string GetFileKey(ObjectInfo info)
306
        {
307
            var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
308
            return key;
309
        }
310

    
311
        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
312
        {
313
            if (accountInfo == null)
314
                throw new ArgumentNullException("accountInfo");
315
            if (action==null)
316
                throw new ArgumentNullException("action");
317
            if (action.LocalFile==null)
318
                throw new ArgumentException("The action's local file is not specified","action");
319
            if (!Path.IsPathRooted(action.LocalFile.FullName))
320
                throw new ArgumentException("The action's local file path must be absolute","action");
321
            if (action.CloudFile== null)
322
                throw new ArgumentException("The action's cloud file is not specified", "action");
323
            Contract.EndContractBlock();
324

    
325
            var localFile = action.LocalFile;
326
            var cloudFile = action.CloudFile;
327
            var downloadPath=action.LocalFile.GetProperCapitalization();
328

    
329
            var cloudHash = cloudFile.Hash.ToLower();
330
            var localHash = action.LocalHash.Value.ToLower();
331
            var topHash = action.TopHash.Value.ToLower();
332

    
333
            //Not enough to compare only the local hashes, also have to compare the tophashes
334
            
335
            //If any of the hashes match, we are done
336
            if ((cloudHash == localHash || cloudHash == topHash))
337
            {
338
                Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
339
                return;
340
            }
341

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

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

    
384
        private void ReportConflict(string downloadPath)
385
        {
386
            if (String.IsNullOrWhiteSpace(downloadPath))
387
                throw new ArgumentNullException("downloadPath");
388
            Contract.EndContractBlock();
389

    
390
            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
391
            UpdateStatus(PithosStatus.HasConflicts);
392
            var message = String.Format("Conflict detected for file {0}", downloadPath);
393
            Log.Warn(message);
394
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
395
        }
396

    
397
        public void Post(CloudAction cloudAction)
398
        {
399
            if (cloudAction == null)
400
                throw new ArgumentNullException("cloudAction");
401
            if (cloudAction.AccountInfo==null)
402
                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
403
            Contract.EndContractBlock();
404

    
405
            _pauseAgent.Wait();
406

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

    
435
       /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
436
        {
437
            public bool Equals(ObjectInfo x, ObjectInfo y)
438
            {
439
                return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
440
            }
441

    
442
            public int GetHashCode(ObjectInfo obj)
443
            {
444
                return obj.Name.ToLower().GetHashCode();
445
            }
446
        }*/
447

    
448
        public void SynchNow()
449
        {             
450
            if (_tcs!=null)
451
                _tcs.TrySetResult(true);
452
            else
453
            {
454
                //TODO: This may be OK for testing purposes, but we have no guarantee that it will
455
                //work properly in production
456
                PollRemoteFiles(repeat:false);
457
            }
458
        }
459

    
460
        //Remote files are polled periodically. Any changes are processed
461
        public async Task PollRemoteFiles(DateTime? since = null,bool repeat=true)
462
        {
463
            UpdateStatus(PithosStatus.Syncing);
464
            StatusNotification.Notify(new PollNotification());
465

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

    
476
                    var tasks = from accountInfo in _accounts
477
                                select ProcessAccountFiles(accountInfo, since);
478

    
479
                    await TaskEx.WhenAll(tasks.ToList());
480
                                        
481
                    _firstPoll = false;
482
                    //Reschedule the poll with the current timestamp as a "since" value
483
                    if (repeat)
484
                        nextSince = current;
485
                    else
486
                        return;
487
                }
488
                catch (Exception ex)
489
                {
490
                    Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
491
                    //In case of failure retry with the same "since" value
492
                }
493
                
494
                UpdateStatus(PithosStatus.InSynch);
495
                //Wait for the polling interval to pass or the Manual flat to be toggled
496
                nextSince = await WaitForScheduledOrManualPoll(nextSince);
497

    
498
                PollRemoteFiles(nextSince);
499

    
500
            }
501
        }
502

    
503
        private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
504
        {            
505
            _tcs = new TaskCompletionSource<bool>();
506
            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), _agent.CancellationToken);
507
            var signaledTask = await TaskEx.WhenAny(_tcs.Task, wait);
508
            //If polling is signalled by SynchNow, ignore the since tag
509
            if (signaledTask is Task<bool>)
510
                return null;
511
            return since;
512
        }
513

    
514
        public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
515
        {   
516
            if (accountInfo==null)
517
                throw new ArgumentNullException("accountInfo");
518
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
519
                throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
520
            Contract.EndContractBlock();
521

    
522

    
523
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
524
            {
525
                _pauseAgent.Wait();
526

    
527
                Log.Info("Scheduled");
528
                var client=new CloudFilesClient(accountInfo);
529

    
530
                var containers = client.ListContainers(accountInfo.UserName);
531

    
532

    
533
                CreateContainerFolders(accountInfo, containers);
534

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

    
548
                    var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => client.ListSharedObjects(since), "shared");
549
                    listObjects.Add(listShared);
550
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
551

    
552
                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
553
                    {
554
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
555

    
556
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
557
                        var remoteObjects = from objectList in listTasks
558
                                            where (string) objectList.AsyncState != "trash"
559
                                            from obj in objectList.Result
560
                                            select obj;
561

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

    
590
                        var trashObjects = dict["trash"].Result;
591
                        var sharedObjects = dict["shared"].Result;
592

    
593
                        //Items with the same name, hash may be both in the container and the trash
594
                        //Don't delete items that exist in the container
595
                        var realTrash = from trash in trashObjects
596
                                        where
597
                                            !remoteObjects.Any(
598
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
599
                                        select trash;
600
                        ProcessTrashedFiles(accountInfo, realTrash);
601

    
602

    
603
                        var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
604
                                     let name = info.Name
605
                                     where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
606
                                           !name.StartsWith(FolderConstants.CacheFolder + "/",
607
                                                            StringComparison.InvariantCultureIgnoreCase)
608
                                     select info).ToList();
609

    
610

    
611

    
612
                        ProcessDeletedFiles(accountInfo, cleanRemotes, pollTime);
613

    
614
                        //Create a list of actions from the remote files
615
                        var allActions = ObjectsToActions(accountInfo, cleanRemotes);
616

    
617
                        
618
                        //var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
619

    
620
                        //And remove those that are already being processed by the agent
621
                        var distinctActions = allActions
622
                            .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
623
                            .ToList();
624

    
625
                        //Queue all the actions
626
                        foreach (var message in distinctActions)
627
                        {
628
                            Post(message);
629
                        }
630

    
631
                        Log.Info("[LISTENER] End Processing");
632
                    }
633
                }
634
                catch (Exception ex)
635
                {
636
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
637
                    return;
638
                }
639

    
640
                Log.Info("[LISTENER] Finished");
641

    
642
            }
643
        }
644

    
645
        internal class ObjectInfoComparer:EqualityComparer<ObjectInfo>
646
        {
647
            public override bool Equals(ObjectInfo x, ObjectInfo y)
648
            {
649
                return (x.Account == y.Account &&
650
                        x.Container == y.Container &&
651
                        x.Name == y.Name);
652
            }
653

    
654
            public override int GetHashCode(ObjectInfo obj)
655
            {
656
                return String.Join("/",obj.Account,obj.Container,obj.Name).GetHashCode();
657
            }
658
        }
659

    
660
        Dictionary<string, List<ObjectInfo>> _currentSnapshot = new Dictionary<string, List<ObjectInfo>>();
661
        Dictionary<string, List<ObjectInfo>> _previousSnapshot = new Dictionary<string, List<ObjectInfo>>();
662

    
663
        /// <summary>
664
        /// Deletes local files that are not found in the list of cloud files
665
        /// </summary>
666
        /// <param name="accountInfo"></param>
667
        /// <param name="cloudFiles"></param>
668
        /// <param name="pollTime"></param>
669
        private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime)
670
        {
671
            if (accountInfo == null)
672
                throw new ArgumentNullException("accountInfo");
673
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
674
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
675
            if (cloudFiles == null)
676
                throw new ArgumentNullException("cloudFiles");
677
            Contract.EndContractBlock();
678

    
679
            if (_previousSnapshot.ContainsKey(accountInfo.UserName) && _currentSnapshot.ContainsKey(accountInfo.UserName))
680
                _previousSnapshot[accountInfo.UserName] = _currentSnapshot[accountInfo.UserName] ?? new List<ObjectInfo>();
681
            else
682
            {
683
                _previousSnapshot[accountInfo.UserName]=new List<ObjectInfo>();
684
            }
685

    
686
            _currentSnapshot[accountInfo.UserName] = cloudFiles.ToList();
687

    
688
            var deletedObjects = _previousSnapshot[accountInfo.UserName].Except(_currentSnapshot[accountInfo.UserName], new ObjectInfoComparer()).ToList();
689

    
690
            
691
            //On the first run
692
            if (_firstPoll)
693
            {
694
                //Only consider files that are not being modified, ie they are in the Unchanged state            
695
                var deleteCandidates = FileState.Queryable.Where(state =>
696
                    state.FilePath.StartsWith(accountInfo.AccountPath)
697
                    && state.FileStatus == FileStatus.Unchanged).ToList();
698

    
699

    
700
                //TODO: filesToDelete must take into account the Others container            
701
                var filesToDelete = (from deleteCandidate in deleteCandidates
702
                                         let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
703
                                         let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
704
                                     where
705
                                         !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)
706
                                     select localFile).ToList();
707
            
708

    
709

    
710
                //Set the status of missing files to Conflict
711
                foreach (var item in filesToDelete)
712
                {
713
                    //Try to acquire a gate on the file, to take into account files that have been dequeued
714
                    //and are being processed
715
                    using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
716
                    {
717
                        if (gate.Failed)
718
                            continue;
719
                        StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);
720
                    }
721
                }
722
                UpdateStatus(PithosStatus.HasConflicts);
723
                StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted",filesToDelete.Count));
724
                StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count), TraceLevel.Info);
725
            }
726
            else
727
            {
728
                var deletedFiles = new List<FileSystemInfo>();
729
                foreach (var objectInfo in deletedObjects)
730
                {
731
                    var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
732
                    var item = GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);
733
                    if (item.Exists)
734
                    {
735
                        //Try to acquire a gate on the file, to take into account files that have been dequeued
736
                        //and are being processed
737
                        //TODO: The gate is not enough. Perhaps we need to keep a journal of processed files and check against
738
                        //that as well.
739
/*
740
                        using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
741
                        {
742
                            if (gate.Failed)
743
                                continue;
744
*/
745
                            if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
746
                            {
747
                                item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
748

    
749
                            }
750
                            item.Delete();
751
                            DateTime lastDate;
752
                            _lastSeen.TryRemove(item.FullName, out lastDate);
753
                            deletedFiles.Add(item);
754
/*
755
                        }
756
*/
757
                    }
758
                    StatusKeeper.ClearFileStatus(item.FullName);
759
                    
760
                }
761
                StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count), TraceLevel.Info);
762
            }
763

    
764
        }
765

    
766
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
767
        {
768
            var containerPaths = from container in containers
769
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
770
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
771
                                 select containerPath;
772

    
773
            foreach (var path in containerPaths)
774
            {
775
                Directory.CreateDirectory(path);
776
            }
777
        }
778

    
779
        //Creates an appropriate action for each server file
780
        private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
781
        {
782
            if (remote==null)
783
                throw new ArgumentNullException();
784
            Contract.EndContractBlock();
785
            var fileAgent = GetFileAgent(accountInfo);
786

    
787
            //In order to avoid multiple iterations over the files, we iterate only once
788
            //over the remote files
789
            foreach (var objectInfo in remote)
790
            {
791
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
792
                //and remove any matching objects from the list, adding them to the commonObjects list
793
                
794
                if (fileAgent.Exists(relativePath))
795
                {
796
                    //If a directory object already exists, we don't need to perform any other action                    
797
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
798
                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
799
                        continue;
800
                    using (new SessionScope(FlushAction.Never))
801
                    {
802
                        var state =  StatusKeeper.GetStateByFilePath(localFile.FullName);
803
                        _lastSeen[localFile.FullName] = DateTime.Now;
804
                        //FileState.FindByFilePath(localFile.FullName);
805
                        //Common files should be checked on a per-case basis to detect differences, which is newer
806

    
807
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
808
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
809
                                                     accountInfo.BlockHash);
810
                    }
811
                }
812
                else
813
                {
814
                    //If there is no match we add them to the localFiles list
815
                    //but only if the file is not marked for deletion
816
                    var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
817
                    var fileStatus = StatusKeeper.GetFileStatus(targetFile);
818
                    if (fileStatus != FileStatus.Deleted)
819
                    {
820
                        //Remote files should be downloaded
821
                        yield return new CloudDownloadAction(accountInfo,objectInfo);
822
                    }
823
                }
824
            }            
825
        }
826

    
827
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
828
        {
829
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
830
        }
831

    
832
        private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
833
        {
834
            var fileAgent = GetFileAgent(accountInfo);
835
            foreach (var trashObject in trashObjects)
836
            {
837
                var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
838
                //HACK: Assume only the "pithos" container is used. Must find out what happens when
839
                //deleting a file from a different container
840
                var relativePath = Path.Combine("pithos", barePath);
841
                fileAgent.Delete(relativePath);                                
842
            }
843
        }
844

    
845

    
846
        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
847
        {
848
            if (accountInfo==null)
849
                throw new ArgumentNullException("accountInfo");
850
            if (action==null)
851
                throw new ArgumentNullException("action");
852
            if (action.CloudFile==null)
853
                throw new ArgumentException("CloudFile","action");
854
            if (action.LocalFile==null)
855
                throw new ArgumentException("LocalFile","action");
856
            if (action.OldLocalFile==null)
857
                throw new ArgumentException("OldLocalFile","action");
858
            if (action.OldCloudFile==null)
859
                throw new ArgumentException("OldCloudFile","action");
860
            Contract.EndContractBlock();
861
            
862
            
863
            var newFilePath = action.LocalFile.FullName;
864
            
865
            //How do we handle concurrent renames and deletes/uploads/downloads?
866
            //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
867
            //  This should never happen as the network agent executes only one action at a time
868
            //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
869
            //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
870
            //  same name will fail.
871
            //  This should never happen as the network agent executes only one action at a time.
872
            //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
873
            //  to remove the rename from the queue.
874
            //  We can probably ignore this case. It will result in an error which should be ignored            
875

    
876
            
877
            //The local file is already renamed
878
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
879

    
880

    
881
            var account = action.CloudFile.Account ?? accountInfo.UserName;
882
            var container = action.CloudFile.Container;
883
            
884
            var client = new CloudFilesClient(accountInfo);
885
            //TODO: What code is returned when the source file doesn't exist?
886
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
887

    
888
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
889
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
890
            NativeMethods.RaiseChangeNotification(newFilePath);
891
        }
892

    
893
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
894
        {
895
            if (accountInfo == null)
896
                throw new ArgumentNullException("accountInfo");
897
            if (cloudFile==null)
898
                throw new ArgumentNullException("cloudFile");
899

    
900
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
901
                throw new ArgumentException("Invalid container", "cloudFile");
902
            Contract.EndContractBlock();
903
            
904
            var fileAgent = GetFileAgent(accountInfo);
905

    
906
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
907
            {
908
                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
909
                var info = fileAgent.GetFileSystemInfo(fileName);                
910
                var fullPath = info.FullName.ToLower();
911

    
912
                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
913

    
914
                var account = cloudFile.Account ?? accountInfo.UserName;
915
                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
916

    
917
                var client = new CloudFilesClient(accountInfo);
918
                client.DeleteObject(account, container, cloudFile.Name);
919

    
920
                StatusKeeper.ClearFileStatus(fullPath);
921
            }
922
        }
923

    
924
        //Download a file.
925
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
926
        {
927
            if (accountInfo == null)
928
                throw new ArgumentNullException("accountInfo");
929
            if (cloudFile == null)
930
                throw new ArgumentNullException("cloudFile");
931
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
932
                throw new ArgumentNullException("cloudFile");
933
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
934
                throw new ArgumentNullException("cloudFile");
935
            if (String.IsNullOrWhiteSpace(filePath))
936
                throw new ArgumentNullException("filePath");
937
            if (!Path.IsPathRooted(filePath))
938
                throw new ArgumentException("The filePath must be rooted", "filePath");
939
            Contract.EndContractBlock();
940
            
941

    
942
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
943
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
944

    
945
            var url = relativeUrl.ToString();
946
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
947
                return;
948

    
949

    
950
            //Are we already downloading or uploading the file? 
951
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
952
            {
953
                if (gate.Failed)
954
                    return;
955
                //The file's hashmap will be stored in the same location with the extension .hashmap
956
                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
957
                
958
                var client = new CloudFilesClient(accountInfo);
959
                var account = cloudFile.Account;
960
                var container = cloudFile.Container;
961

    
962
                if (cloudFile.Content_Type == @"application/directory")
963
                {
964
                    if (!Directory.Exists(localPath))
965
                        Directory.CreateDirectory(localPath);
966
                }
967
                else
968
                {                    
969
                    //Retrieve the hashmap from the server
970
                    var serverHash = await client.GetHashMap(account, container, url);
971
                    //If it's a small file
972
                    if (serverHash.Hashes.Count == 1)
973
                        //Download it in one go
974
                        await
975
                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
976
                        //Otherwise download it block by block
977
                    else
978
                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
979

    
980
                    if (cloudFile.AllowedTo == "read")
981
                    {
982
                        var attributes = File.GetAttributes(localPath);
983
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
984
                    }
985
                }
986

    
987
                //Now we can store the object's metadata without worrying about ghost status entries
988
                StatusKeeper.StoreInfo(localPath, cloudFile);
989
                
990
            }
991
        }
992

    
993
        //Download a small file with a single GET operation
994
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
995
        {
996
            if (client == null)
997
                throw new ArgumentNullException("client");
998
            if (cloudFile==null)
999
                throw new ArgumentNullException("cloudFile");
1000
            if (relativeUrl == null)
1001
                throw new ArgumentNullException("relativeUrl");
1002
            if (String.IsNullOrWhiteSpace(filePath))
1003
                throw new ArgumentNullException("filePath");
1004
            if (!Path.IsPathRooted(filePath))
1005
                throw new ArgumentException("The localPath must be rooted", "filePath");
1006
            Contract.EndContractBlock();
1007

    
1008
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
1009
            //If the file already exists
1010
            if (File.Exists(localPath))
1011
            {
1012
                //First check with MD5 as this is a small file
1013
                var localMD5 = Signature.CalculateMD5(localPath);
1014
                var cloudHash=serverHash.TopHash.ToHashString();
1015
                if (localMD5==cloudHash)
1016
                    return;
1017
                //Then check with a treehash
1018
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
1019
                var localHash = localTreeHash.TopHash.ToHashString();
1020
                if (localHash==cloudHash)
1021
                    return;
1022
            }
1023
            StatusNotification.Notify(new CloudNotification { Data = cloudFile });
1024

    
1025
            var fileAgent = GetFileAgent(accountInfo);
1026
            //Calculate the relative file path for the new file
1027
            var relativePath = relativeUrl.RelativeUriToFilePath();
1028
            //The file will be stored in a temporary location while downloading with an extension .download
1029
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
1030
            //Make sure the target folder exists. DownloadFileTask will not create the folder
1031
            var tempFolder = Path.GetDirectoryName(tempPath);
1032
            if (!Directory.Exists(tempFolder))
1033
                Directory.CreateDirectory(tempFolder);
1034

    
1035
            //Download the object to the temporary location
1036
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
1037

    
1038
            //Create the local folder if it doesn't exist (necessary for shared objects)
1039
            var localFolder = Path.GetDirectoryName(localPath);
1040
            if (!Directory.Exists(localFolder))
1041
                Directory.CreateDirectory(localFolder);            
1042
            //And move it to its actual location once downloading is finished
1043
            if (File.Exists(localPath))
1044
                File.Replace(tempPath,localPath,null,true);
1045
            else
1046
                File.Move(tempPath,localPath);
1047
            //Notify listeners that a local file has changed
1048
            StatusNotification.NotifyChangedFile(localPath);
1049

    
1050
                       
1051
        }
1052

    
1053
        //Download a file asynchronously using blocks
1054
        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
1055
        {
1056
            if (client == null)
1057
                throw new ArgumentNullException("client");
1058
            if (cloudFile == null)
1059
                throw new ArgumentNullException("cloudFile");
1060
            if (relativeUrl == null)
1061
                throw new ArgumentNullException("relativeUrl");
1062
            if (String.IsNullOrWhiteSpace(filePath))
1063
                throw new ArgumentNullException("filePath");
1064
            if (!Path.IsPathRooted(filePath))
1065
                throw new ArgumentException("The filePath must be rooted", "filePath");
1066
            if (serverHash == null)
1067
                throw new ArgumentNullException("serverHash");
1068
            Contract.EndContractBlock();
1069
            
1070
           var fileAgent = GetFileAgent(accountInfo);
1071
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
1072
            
1073
            //Calculate the relative file path for the new file
1074
            var relativePath = relativeUrl.RelativeUriToFilePath();
1075
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
1076

    
1077
            
1078
                        
1079
            //Calculate the file's treehash
1080
            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
1081
                
1082
            //And compare it with the server's hash
1083
            var upHashes = serverHash.GetHashesAsStrings();
1084
            var localHashes = treeHash.HashDictionary;
1085
            for (int i = 0; i < upHashes.Length; i++)
1086
            {
1087
                //For every non-matching hash
1088
                var upHash = upHashes[i];
1089
                if (!localHashes.ContainsKey(upHash))
1090
                {
1091
                    StatusNotification.Notify(new CloudNotification { Data = cloudFile });
1092

    
1093
                    if (blockUpdater.UseOrphan(i, upHash))
1094
                    {
1095
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
1096
                        continue;
1097
                    }
1098
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
1099
                    var start = i*serverHash.BlockSize;
1100
                    //To download the last block just pass a null for the end of the range
1101
                    long? end = null;
1102
                    if (i < upHashes.Length - 1 )
1103
                        end= ((i + 1)*serverHash.BlockSize) ;
1104
                            
1105
                    //Download the missing block
1106
                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
1107

    
1108
                    //and store it
1109
                    blockUpdater.StoreBlock(i, block);
1110

    
1111

    
1112
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
1113
                }
1114
            }
1115

    
1116
            //Want to avoid notifications if no changes were made
1117
            var hasChanges = blockUpdater.HasBlocks;
1118
            blockUpdater.Commit();
1119
            
1120
            if (hasChanges)
1121
                //Notify listeners that a local file has changed
1122
                StatusNotification.NotifyChangedFile(localPath);
1123

    
1124
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
1125
        }
1126

    
1127

    
1128
        private async Task UploadCloudFile(CloudAction action)
1129
        {
1130
            if (action == null)
1131
                throw new ArgumentNullException("action");           
1132
            Contract.EndContractBlock();
1133

    
1134
            try
1135
            {                
1136
                var accountInfo = action.AccountInfo;
1137

    
1138
                var fileInfo = action.LocalFile;
1139

    
1140
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
1141
                    return;
1142
                
1143
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
1144
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
1145
                {
1146
                    var parts = relativePath.Split('\\');
1147
                    var accountName = parts[1];
1148
                    var oldName = accountInfo.UserName;
1149
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
1150
                    var nameIndex = absoluteUri.IndexOf(oldName);
1151
                    var root = absoluteUri.Substring(0, nameIndex);
1152

    
1153
                    accountInfo = new AccountInfo
1154
                    {
1155
                        UserName = accountName,
1156
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
1157
                        StorageUri = new Uri(root + accountName),
1158
                        BlockHash = accountInfo.BlockHash,
1159
                        BlockSize = accountInfo.BlockSize,
1160
                        Token = accountInfo.Token
1161
                    };
1162
                }
1163

    
1164

    
1165
                var fullFileName = fileInfo.GetProperCapitalization();
1166
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
1167
                {
1168
                    //Abort if the file is already being uploaded or downloaded
1169
                    if (gate.Failed)
1170
                        return;
1171

    
1172
                    var cloudFile = action.CloudFile;
1173
                    var account = cloudFile.Account ?? accountInfo.UserName;
1174

    
1175
                    var client = new CloudFilesClient(accountInfo);                    
1176
                    //Even if GetObjectInfo times out, we can proceed with the upload            
1177
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
1178

    
1179
                    //If this is a read-only file, do not upload changes
1180
                    if (info.AllowedTo == "read")
1181
                        return;
1182
                    
1183
                    //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
1184
                    if (fileInfo is DirectoryInfo)
1185
                    {
1186
                        //If the directory doesn't exist the Hash property will be empty
1187
                        if (String.IsNullOrWhiteSpace(info.Hash))
1188
                            //Go on and create the directory
1189
                            await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
1190
                    }
1191
                    else
1192
                    {
1193

    
1194
                        var cloudHash = info.Hash.ToLower();
1195

    
1196
                        var hash = action.LocalHash.Value;
1197
                        var topHash = action.TopHash.Value;
1198

    
1199
                        //If the file hashes match, abort the upload
1200
                        if (hash == cloudHash || topHash == cloudHash)
1201
                        {
1202
                            //but store any metadata changes 
1203
                            StatusKeeper.StoreInfo(fullFileName, info);
1204
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1205
                            return;
1206
                        }
1207

    
1208

    
1209
                        //Mark the file as modified while we upload it
1210
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1211
                        //And then upload it
1212

    
1213
                        //Upload even small files using the Hashmap. The server may already contain
1214
                        //the relevant block
1215

    
1216
                        //First, calculate the tree hash
1217
                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1218
                                                                              accountInfo.BlockHash);
1219

    
1220
                        await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1221
                    }
1222
                    //If everything succeeds, change the file and overlay status to normal
1223
                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1224
                }
1225
                //Notify the Shell to update the overlays
1226
                NativeMethods.RaiseChangeNotification(fullFileName);
1227
                StatusNotification.NotifyChangedFile(fullFileName);
1228
            }
1229
            catch (AggregateException ex)
1230
            {
1231
                var exc = ex.InnerException as WebException;
1232
                if (exc == null)
1233
                    throw ex.InnerException;
1234
                if (HandleUploadWebException(action, exc)) 
1235
                    return;
1236
                throw;
1237
            }
1238
            catch (WebException ex)
1239
            {
1240
                if (HandleUploadWebException(action, ex))
1241
                    return;
1242
                throw;
1243
            }
1244
            catch (Exception ex)
1245
            {
1246
                Log.Error("Unexpected error while uploading file", ex);
1247
                throw;
1248
            }
1249

    
1250
        }
1251

    
1252
        //Returns true if an action concerns a file that was deleted
1253
        private bool IsDeletedFile(CloudAction action)
1254
        {
1255
            //Doesn't work for actions targeting shared files
1256
            if (action.IsShared)
1257
                return false;
1258
            var key = GetFileKey(action.CloudFile);
1259
            DateTime entryDate;
1260
            if (_deletedFiles.TryGetValue(key, out entryDate))
1261
            {
1262
                //If the delete entry was created after this action, abort the action
1263
                if (entryDate > action.Created)
1264
                    return true;
1265
                //Otherwise, remove the stale entry 
1266
                _deletedFiles.TryRemove(key, out entryDate);
1267
            }
1268
            return false;
1269
        }
1270

    
1271
        private bool HandleUploadWebException(CloudAction action, WebException exc)
1272
        {
1273
            var response = exc.Response as HttpWebResponse;
1274
            if (response == null)
1275
                throw exc;
1276
            if (response.StatusCode == HttpStatusCode.Unauthorized)
1277
            {
1278
                Log.Error("Not allowed to upload file", exc);
1279
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1280
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1281
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
1282
                return true;
1283
            }
1284
            return false;
1285
        }
1286

    
1287
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1288
        {
1289
            if (accountInfo == null)
1290
                throw new ArgumentNullException("accountInfo");
1291
            if (cloudFile==null)
1292
                throw new ArgumentNullException("cloudFile");
1293
            if (fileInfo == null)
1294
                throw new ArgumentNullException("fileInfo");
1295
            if (String.IsNullOrWhiteSpace(url))
1296
                throw new ArgumentNullException(url);
1297
            if (treeHash==null)
1298
                throw new ArgumentNullException("treeHash");
1299
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1300
                throw new ArgumentException("Invalid container","cloudFile");
1301
            Contract.EndContractBlock();
1302

    
1303
            var fullFileName = fileInfo.GetProperCapitalization();
1304

    
1305
            var account = cloudFile.Account ?? accountInfo.UserName;
1306
            var container = cloudFile.Container ;
1307

    
1308
            var client = new CloudFilesClient(accountInfo);
1309
            //Send the hashmap to the server            
1310
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
1311
            //If the server returns no missing hashes, we are done
1312
            while (missingHashes.Count > 0)
1313
            {
1314

    
1315
                var buffer = new byte[accountInfo.BlockSize];
1316
                foreach (var missingHash in missingHashes)
1317
                {
1318
                    //Find the proper block
1319
                    var blockIndex = treeHash.HashDictionary[missingHash];
1320
                    var offset = blockIndex*accountInfo.BlockSize;
1321

    
1322
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1323

    
1324
                    try
1325
                    {
1326
                        //And upload the block                
1327
                        await client.PostBlock(account, container, buffer, 0, read);
1328
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1329
                    }
1330
                    catch (Exception exc)
1331
                    {
1332
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1333
                    }
1334

    
1335
                }
1336

    
1337
                //Repeat until there are no more missing hashes                
1338
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
1339
            }
1340
        }
1341

    
1342

    
1343
        public void AddAccount(AccountInfo accountInfo)
1344
        {            
1345
            if (!_accounts.Contains(accountInfo))
1346
                _accounts.Add(accountInfo);
1347
        }
1348
    }
1349

    
1350
   
1351

    
1352

    
1353
}