Statistics
| Branch: | Revision:

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

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

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

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

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

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

    
238
            var accountInfo = action.AccountInfo;
239

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

    
244
                var cloudFile = action.CloudFile;
245

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

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

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

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

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

    
300
                }
301
            }
302
        }
303

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

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

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

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

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

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

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

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

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

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

    
404
            _pauseAgent.Wait();
405

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

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

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

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

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

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

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

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

    
497
                PollRemoteFiles(nextSince);
498

    
499
            }
500
        }
501

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

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

    
521

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

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

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

    
531

    
532
                CreateContainerFolders(accountInfo, containers);
533

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

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

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

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

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

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

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

    
601

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

    
609

    
610

    
611
                        ProcessDeletedFiles(accountInfo, cleanRemotes, pollTime);
612

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

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

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

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

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

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

    
641
            }
642
        }
643

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

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

    
667
            var d0 = FileState.Queryable
668
                .Where(state => 
669
                            state.FilePath.StartsWith(accountInfo.AccountPath)).ToList();
670
            
671
            var d1 = FileState.Queryable
672
                .Where(state => state.Modified <= pollTime).ToList();
673
            var d2= FileState.Queryable
674
                .Where(state => state.Modified <= pollTime
675
                            &&
676
                            state.FilePath.StartsWith(accountInfo.AccountPath)).ToList();*/
677

    
678
            //Consider for deleteion only files modified before the PREVIOUS poll
679
            //A user may perform a file creation or rename at roughly the same time as a poll. In such a case
680
            //the new file will appear as deleted
681
            var previousPollTime = pollTime.Subtract(TimeSpan.FromMilliseconds(Settings.PollingInterval));
682

    
683
            var deleteCandidates = FileState.Queryable.Where(state => 
684
                state.Modified <= previousPollTime
685
                && state.FilePath.StartsWith(accountInfo.AccountPath)
686
                && state.FileStatus != FileStatus.Conflict).ToList();
687

    
688
            //TODO: filesToDelete must take into account the Others container
689
            var filesToDelete = (from deleteCandidate in deleteCandidates 
690
                         let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath) 
691
                         let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath) 
692
                         where !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath ) 
693
                         //Exclude files enqueued for uploading
694
                         //Large files will not appear on the server for multiple polls. They must not be marked as deleted
695
                         && !_agent.GetEnumerable().Any(action => action.LocalFile.WithProperCapitalization().FullName == localFile.FullName)
696
                         //Do NOT delete files modified since the previous poll
697
                                && localFile.LastAccessTime < previousPollTime
698
                         select localFile).ToList();
699

    
700
            //On the first run
701
            if (_firstPoll)
702
            {
703
                //Set the status of missing files to Conflict
704
                foreach (var item in filesToDelete)
705
                {
706
                    //Try to acquire a gate on the file, to take into account files that have been dequeued
707
                    //and are being processed
708
                    using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
709
                    {
710
                        if (gate.Failed)
711
                            continue;
712
                        StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);
713
                    }
714
                }
715
                UpdateStatus(PithosStatus.HasConflicts);
716
                StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted",filesToDelete.Count));
717
            }
718
            else
719
            {
720
                foreach (var item in filesToDelete)
721
                {
722
                    if (item.Exists)
723
                    {
724
                        //Try to acquire a gate on the file, to take into account files that have been dequeued
725
                        //and are being processed
726
                        //TODO: The gate is not enough. Perhaps we need to keep a journal of processed files and check against
727
                        //that as well.
728
                        using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
729
                        {
730
                            if (gate.Failed)
731
                                continue;
732
                            if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
733
                            {
734
                                item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
735

    
736
                            }
737
                            item.Delete();
738
                        }
739
                    }
740
                    StatusKeeper.ClearFileStatus(item.FullName);
741
                }
742
                StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted",filesToDelete.Count),TraceLevel.Info);
743
            }
744

    
745
        }
746

    
747
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
748
        {
749
            var containerPaths = from container in containers
750
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
751
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
752
                                 select containerPath;
753

    
754
            foreach (var path in containerPaths)
755
            {
756
                Directory.CreateDirectory(path);
757
            }
758
        }
759

    
760
        //Creates an appropriate action for each server file
761
        private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
762
        {
763
            if (remote==null)
764
                throw new ArgumentNullException();
765
            Contract.EndContractBlock();
766
            var fileAgent = GetFileAgent(accountInfo);
767

    
768
            //In order to avoid multiple iterations over the files, we iterate only once
769
            //over the remote files
770
            foreach (var objectInfo in remote)
771
            {
772
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
773
                //and remove any matching objects from the list, adding them to the commonObjects list
774
                
775
                if (fileAgent.Exists(relativePath))
776
                {
777
                    //If a directory object already exists, we don't need to perform any other action                    
778
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
779
                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
780
                        continue;
781
                    using (new SessionScope(FlushAction.Never))
782
                    {
783
                        var state =  StatusKeeper.GetStateByFilePath(localFile.FullName);
784
                        //FileState.FindByFilePath(localFile.FullName);
785
                        //Common files should be checked on a per-case basis to detect differences, which is newer
786

    
787
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
788
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
789
                                                     accountInfo.BlockHash);
790
                    }
791
                }
792
                else
793
                {
794
                    //If there is no match we add them to the localFiles list
795
                    //but only if the file is not marked for deletion
796
                    var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
797
                    var fileStatus = StatusKeeper.GetFileStatus(targetFile);
798
                    if (fileStatus != FileStatus.Deleted)
799
                    {
800
                        //Remote files should be downloaded
801
                        yield return new CloudDownloadAction(accountInfo,objectInfo);
802
                    }
803
                }
804
            }            
805
        }
806

    
807
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
808
        {
809
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
810
        }
811

    
812
        private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
813
        {
814
            var fileAgent = GetFileAgent(accountInfo);
815
            foreach (var trashObject in trashObjects)
816
            {
817
                var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
818
                //HACK: Assume only the "pithos" container is used. Must find out what happens when
819
                //deleting a file from a different container
820
                var relativePath = Path.Combine("pithos", barePath);
821
                fileAgent.Delete(relativePath);                                
822
            }
823
        }
824

    
825

    
826
        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
827
        {
828
            if (accountInfo==null)
829
                throw new ArgumentNullException("accountInfo");
830
            if (action==null)
831
                throw new ArgumentNullException("action");
832
            if (action.CloudFile==null)
833
                throw new ArgumentException("CloudFile","action");
834
            if (action.LocalFile==null)
835
                throw new ArgumentException("LocalFile","action");
836
            if (action.OldLocalFile==null)
837
                throw new ArgumentException("OldLocalFile","action");
838
            if (action.OldCloudFile==null)
839
                throw new ArgumentException("OldCloudFile","action");
840
            Contract.EndContractBlock();
841
            
842
            
843
            var newFilePath = action.LocalFile.FullName;
844
            
845
            //How do we handle concurrent renames and deletes/uploads/downloads?
846
            //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
847
            //  This should never happen as the network agent executes only one action at a time
848
            //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
849
            //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
850
            //  same name will fail.
851
            //  This should never happen as the network agent executes only one action at a time.
852
            //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
853
            //  to remove the rename from the queue.
854
            //  We can probably ignore this case. It will result in an error which should be ignored            
855

    
856
            
857
            //The local file is already renamed
858
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
859

    
860

    
861
            var account = action.CloudFile.Account ?? accountInfo.UserName;
862
            var container = action.CloudFile.Container;
863
            
864
            var client = new CloudFilesClient(accountInfo);
865
            //TODO: What code is returned when the source file doesn't exist?
866
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
867

    
868
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
869
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
870
            NativeMethods.RaiseChangeNotification(newFilePath);
871
        }
872

    
873
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
874
        {
875
            if (accountInfo == null)
876
                throw new ArgumentNullException("accountInfo");
877
            if (cloudFile==null)
878
                throw new ArgumentNullException("cloudFile");
879

    
880
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
881
                throw new ArgumentException("Invalid container", "cloudFile");
882
            Contract.EndContractBlock();
883
            
884
            var fileAgent = GetFileAgent(accountInfo);
885

    
886
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
887
            {
888
                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
889
                var info = fileAgent.GetFileSystemInfo(fileName);                
890
                var fullPath = info.FullName.ToLower();
891

    
892
                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
893

    
894
                var account = cloudFile.Account ?? accountInfo.UserName;
895
                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
896

    
897
                var client = new CloudFilesClient(accountInfo);
898
                client.DeleteObject(account, container, cloudFile.Name);
899

    
900
                StatusKeeper.ClearFileStatus(fullPath);
901
            }
902
        }
903

    
904
        //Download a file.
905
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
906
        {
907
            if (accountInfo == null)
908
                throw new ArgumentNullException("accountInfo");
909
            if (cloudFile == null)
910
                throw new ArgumentNullException("cloudFile");
911
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
912
                throw new ArgumentNullException("cloudFile");
913
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
914
                throw new ArgumentNullException("cloudFile");
915
            if (String.IsNullOrWhiteSpace(filePath))
916
                throw new ArgumentNullException("filePath");
917
            if (!Path.IsPathRooted(filePath))
918
                throw new ArgumentException("The filePath must be rooted", "filePath");
919
            Contract.EndContractBlock();
920
            
921

    
922
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
923
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
924

    
925
            var url = relativeUrl.ToString();
926
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
927
                return;
928

    
929

    
930
            //Are we already downloading or uploading the file? 
931
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
932
            {
933
                if (gate.Failed)
934
                    return;
935
                //The file's hashmap will be stored in the same location with the extension .hashmap
936
                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
937
                
938
                var client = new CloudFilesClient(accountInfo);
939
                var account = cloudFile.Account;
940
                var container = cloudFile.Container;
941

    
942
                if (cloudFile.Content_Type == @"application/directory")
943
                {
944
                    if (!Directory.Exists(localPath))
945
                        Directory.CreateDirectory(localPath);
946
                }
947
                else
948
                {                    
949
                    //Retrieve the hashmap from the server
950
                    var serverHash = await client.GetHashMap(account, container, url);
951
                    //If it's a small file
952
                    if (serverHash.Hashes.Count == 1)
953
                        //Download it in one go
954
                        await
955
                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
956
                        //Otherwise download it block by block
957
                    else
958
                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
959

    
960
                    if (cloudFile.AllowedTo == "read")
961
                    {
962
                        var attributes = File.GetAttributes(localPath);
963
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
964
                    }
965
                }
966

    
967
                //Now we can store the object's metadata without worrying about ghost status entries
968
                StatusKeeper.StoreInfo(localPath, cloudFile);
969
                
970
            }
971
        }
972

    
973
        //Download a small file with a single GET operation
974
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
975
        {
976
            if (client == null)
977
                throw new ArgumentNullException("client");
978
            if (cloudFile==null)
979
                throw new ArgumentNullException("cloudFile");
980
            if (relativeUrl == null)
981
                throw new ArgumentNullException("relativeUrl");
982
            if (String.IsNullOrWhiteSpace(filePath))
983
                throw new ArgumentNullException("filePath");
984
            if (!Path.IsPathRooted(filePath))
985
                throw new ArgumentException("The localPath must be rooted", "filePath");
986
            Contract.EndContractBlock();
987

    
988
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
989
            //If the file already exists
990
            if (File.Exists(localPath))
991
            {
992
                //First check with MD5 as this is a small file
993
                var localMD5 = Signature.CalculateMD5(localPath);
994
                var cloudHash=serverHash.TopHash.ToHashString();
995
                if (localMD5==cloudHash)
996
                    return;
997
                //Then check with a treehash
998
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
999
                var localHash = localTreeHash.TopHash.ToHashString();
1000
                if (localHash==cloudHash)
1001
                    return;
1002
            }
1003
            StatusNotification.Notify(new CloudNotification { Data = cloudFile });
1004

    
1005
            var fileAgent = GetFileAgent(accountInfo);
1006
            //Calculate the relative file path for the new file
1007
            var relativePath = relativeUrl.RelativeUriToFilePath();
1008
            //The file will be stored in a temporary location while downloading with an extension .download
1009
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
1010
            //Make sure the target folder exists. DownloadFileTask will not create the folder
1011
            var tempFolder = Path.GetDirectoryName(tempPath);
1012
            if (!Directory.Exists(tempFolder))
1013
                Directory.CreateDirectory(tempFolder);
1014

    
1015
            //Download the object to the temporary location
1016
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
1017

    
1018
            //Create the local folder if it doesn't exist (necessary for shared objects)
1019
            var localFolder = Path.GetDirectoryName(localPath);
1020
            if (!Directory.Exists(localFolder))
1021
                Directory.CreateDirectory(localFolder);            
1022
            //And move it to its actual location once downloading is finished
1023
            if (File.Exists(localPath))
1024
                File.Replace(tempPath,localPath,null,true);
1025
            else
1026
                File.Move(tempPath,localPath);
1027
            //Notify listeners that a local file has changed
1028
            StatusNotification.NotifyChangedFile(localPath);
1029

    
1030
                       
1031
        }
1032

    
1033
        //Download a file asynchronously using blocks
1034
        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
1035
        {
1036
            if (client == null)
1037
                throw new ArgumentNullException("client");
1038
            if (cloudFile == null)
1039
                throw new ArgumentNullException("cloudFile");
1040
            if (relativeUrl == null)
1041
                throw new ArgumentNullException("relativeUrl");
1042
            if (String.IsNullOrWhiteSpace(filePath))
1043
                throw new ArgumentNullException("filePath");
1044
            if (!Path.IsPathRooted(filePath))
1045
                throw new ArgumentException("The filePath must be rooted", "filePath");
1046
            if (serverHash == null)
1047
                throw new ArgumentNullException("serverHash");
1048
            Contract.EndContractBlock();
1049
            
1050
           var fileAgent = GetFileAgent(accountInfo);
1051
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
1052
            
1053
            //Calculate the relative file path for the new file
1054
            var relativePath = relativeUrl.RelativeUriToFilePath();
1055
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
1056

    
1057
            
1058
                        
1059
            //Calculate the file's treehash
1060
            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
1061
                
1062
            //And compare it with the server's hash
1063
            var upHashes = serverHash.GetHashesAsStrings();
1064
            var localHashes = treeHash.HashDictionary;
1065
            for (int i = 0; i < upHashes.Length; i++)
1066
            {
1067
                //For every non-matching hash
1068
                var upHash = upHashes[i];
1069
                if (!localHashes.ContainsKey(upHash))
1070
                {
1071
                    StatusNotification.Notify(new CloudNotification { Data = cloudFile });
1072

    
1073
                    if (blockUpdater.UseOrphan(i, upHash))
1074
                    {
1075
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
1076
                        continue;
1077
                    }
1078
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
1079
                    var start = i*serverHash.BlockSize;
1080
                    //To download the last block just pass a null for the end of the range
1081
                    long? end = null;
1082
                    if (i < upHashes.Length - 1 )
1083
                        end= ((i + 1)*serverHash.BlockSize) ;
1084
                            
1085
                    //Download the missing block
1086
                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
1087

    
1088
                    //and store it
1089
                    blockUpdater.StoreBlock(i, block);
1090

    
1091

    
1092
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
1093
                }
1094
            }
1095

    
1096
            //Want to avoid notifications if no changes were made
1097
            var hasChanges = blockUpdater.HasBlocks;
1098
            blockUpdater.Commit();
1099
            
1100
            if (hasChanges)
1101
                //Notify listeners that a local file has changed
1102
                StatusNotification.NotifyChangedFile(localPath);
1103

    
1104
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
1105
        }
1106

    
1107

    
1108
        private async Task UploadCloudFile(CloudAction action)
1109
        {
1110
            if (action == null)
1111
                throw new ArgumentNullException("action");           
1112
            Contract.EndContractBlock();
1113

    
1114
            try
1115
            {                
1116
                var accountInfo = action.AccountInfo;
1117

    
1118
                var fileInfo = action.LocalFile;
1119

    
1120
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
1121
                    return;
1122
                
1123
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
1124
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
1125
                {
1126
                    var parts = relativePath.Split('\\');
1127
                    var accountName = parts[1];
1128
                    var oldName = accountInfo.UserName;
1129
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
1130
                    var nameIndex = absoluteUri.IndexOf(oldName);
1131
                    var root = absoluteUri.Substring(0, nameIndex);
1132

    
1133
                    accountInfo = new AccountInfo
1134
                    {
1135
                        UserName = accountName,
1136
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
1137
                        StorageUri = new Uri(root + accountName),
1138
                        BlockHash = accountInfo.BlockHash,
1139
                        BlockSize = accountInfo.BlockSize,
1140
                        Token = accountInfo.Token
1141
                    };
1142
                }
1143

    
1144

    
1145
                var fullFileName = fileInfo.GetProperCapitalization();
1146
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
1147
                {
1148
                    //Abort if the file is already being uploaded or downloaded
1149
                    if (gate.Failed)
1150
                        return;
1151

    
1152
                    var cloudFile = action.CloudFile;
1153
                    var account = cloudFile.Account ?? accountInfo.UserName;
1154

    
1155
                    var client = new CloudFilesClient(accountInfo);                    
1156
                    //Even if GetObjectInfo times out, we can proceed with the upload            
1157
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
1158

    
1159
                    //If this is a read-only file, do not upload changes
1160
                    if (info.AllowedTo == "read")
1161
                        return;
1162
                    
1163
                    //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
1164
                    if (fileInfo is DirectoryInfo)
1165
                    {
1166
                        //If the directory doesn't exist the Hash property will be empty
1167
                        if (String.IsNullOrWhiteSpace(info.Hash))
1168
                            //Go on and create the directory
1169
                            await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
1170
                    }
1171
                    else
1172
                    {
1173

    
1174
                        var cloudHash = info.Hash.ToLower();
1175

    
1176
                        var hash = action.LocalHash.Value;
1177
                        var topHash = action.TopHash.Value;
1178

    
1179
                        //If the file hashes match, abort the upload
1180
                        if (hash == cloudHash || topHash == cloudHash)
1181
                        {
1182
                            //but store any metadata changes 
1183
                            StatusKeeper.StoreInfo(fullFileName, info);
1184
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
1185
                            return;
1186
                        }
1187

    
1188

    
1189
                        //Mark the file as modified while we upload it
1190
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
1191
                        //And then upload it
1192

    
1193
                        //Upload even small files using the Hashmap. The server may already contain
1194
                        //the relevant block
1195

    
1196
                        //First, calculate the tree hash
1197
                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
1198
                                                                              accountInfo.BlockHash);
1199

    
1200
                        await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1201
                    }
1202
                    //If everything succeeds, change the file and overlay status to normal
1203
                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1204
                }
1205
                //Notify the Shell to update the overlays
1206
                NativeMethods.RaiseChangeNotification(fullFileName);
1207
                StatusNotification.NotifyChangedFile(fullFileName);
1208
            }
1209
            catch (AggregateException ex)
1210
            {
1211
                var exc = ex.InnerException as WebException;
1212
                if (exc == null)
1213
                    throw ex.InnerException;
1214
                if (HandleUploadWebException(action, exc)) 
1215
                    return;
1216
                throw;
1217
            }
1218
            catch (WebException ex)
1219
            {
1220
                if (HandleUploadWebException(action, ex))
1221
                    return;
1222
                throw;
1223
            }
1224
            catch (Exception ex)
1225
            {
1226
                Log.Error("Unexpected error while uploading file", ex);
1227
                throw;
1228
            }
1229

    
1230
        }
1231

    
1232
        private bool IsDeletedFile(CloudAction action)
1233
        {            
1234
            var key = GetFileKey(action.CloudFile);
1235
            DateTime entryDate;
1236
            if (_deletedFiles.TryGetValue(key, out entryDate))
1237
            {
1238
                //If the delete entry was created after this action, abort the action
1239
                if (entryDate > action.Created)
1240
                    return true;
1241
                //Otherwise, remove the stale entry 
1242
                _deletedFiles.TryRemove(key, out entryDate);
1243
            }
1244
            return false;
1245
        }
1246

    
1247
        private bool HandleUploadWebException(CloudAction action, WebException exc)
1248
        {
1249
            var response = exc.Response as HttpWebResponse;
1250
            if (response == null)
1251
                throw exc;
1252
            if (response.StatusCode == HttpStatusCode.Unauthorized)
1253
            {
1254
                Log.Error("Not allowed to upload file", exc);
1255
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1256
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1257
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
1258
                return true;
1259
            }
1260
            return false;
1261
        }
1262

    
1263
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1264
        {
1265
            if (accountInfo == null)
1266
                throw new ArgumentNullException("accountInfo");
1267
            if (cloudFile==null)
1268
                throw new ArgumentNullException("cloudFile");
1269
            if (fileInfo == null)
1270
                throw new ArgumentNullException("fileInfo");
1271
            if (String.IsNullOrWhiteSpace(url))
1272
                throw new ArgumentNullException(url);
1273
            if (treeHash==null)
1274
                throw new ArgumentNullException("treeHash");
1275
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1276
                throw new ArgumentException("Invalid container","cloudFile");
1277
            Contract.EndContractBlock();
1278

    
1279
            var fullFileName = fileInfo.GetProperCapitalization();
1280

    
1281
            var account = cloudFile.Account ?? accountInfo.UserName;
1282
            var container = cloudFile.Container ;
1283

    
1284
            var client = new CloudFilesClient(accountInfo);
1285
            //Send the hashmap to the server            
1286
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
1287
            //If the server returns no missing hashes, we are done
1288
            while (missingHashes.Count > 0)
1289
            {
1290

    
1291
                var buffer = new byte[accountInfo.BlockSize];
1292
                foreach (var missingHash in missingHashes)
1293
                {
1294
                    //Find the proper block
1295
                    var blockIndex = treeHash.HashDictionary[missingHash];
1296
                    var offset = blockIndex*accountInfo.BlockSize;
1297

    
1298
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1299

    
1300
                    try
1301
                    {
1302
                        //And upload the block                
1303
                        await client.PostBlock(account, container, buffer, 0, read);
1304
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1305
                    }
1306
                    catch (Exception exc)
1307
                    {
1308
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1309
                    }
1310

    
1311
                }
1312

    
1313
                //Repeat until there are no more missing hashes                
1314
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
1315
            }
1316
        }
1317

    
1318

    
1319
        public void AddAccount(AccountInfo accountInfo)
1320
        {            
1321
            if (!_accounts.Contains(accountInfo))
1322
                _accounts.Add(accountInfo);
1323
        }
1324
    }
1325

    
1326
   
1327

    
1328

    
1329
}