Statistics
| Branch: | Revision:

root / trunk / Pithos.Network / CloudFilesClient.cs @ c945b450

History | View | Annotate | Download (61.1 kB)

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

    
43
// **CloudFilesClient** provides a simple client interface to CloudFiles and Pithos
44
//
45
// The class provides methods to upload/download files, delete files, manage containers
46

    
47

    
48
using System;
49
using System.Collections.Generic;
50
using System.Collections.Specialized;
51
using System.ComponentModel.Composition;
52
using System.Diagnostics;
53
using System.Diagnostics.Contracts;
54
using System.IO;
55
using System.Linq;
56
using System.Net;
57
using System.Reflection;
58
using System.Security.Cryptography;
59
using System.Text;
60
using System.Threading;
61
using System.Threading.Tasks;
62
using Newtonsoft.Json;
63
using Pithos.Interfaces;
64
using log4net;
65

    
66
namespace Pithos.Network
67
{
68
    [Export(typeof(ICloudClient))]
69
    public class CloudFilesClient:ICloudClient
70
    {
71
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
72

    
73
        //CloudFilesClient uses *_baseClient* internally to communicate with the server
74
        //RestClient provides a REST-friendly interface over the standard WebClient.
75
        private RestClient _baseClient;
76
        
77

    
78
        //During authentication the client provides a UserName 
79
        public string UserName { get; set; }
80
        
81
        //and and ApiKey to the server
82
        public string ApiKey { get; set; }
83
        
84
        //And receives an authentication Token. This token must be provided in ALL other operations,
85
        //in the X-Auth-Token header
86
        private string _token;
87
        public string Token
88
        {
89
            get { return _token; }
90
            set
91
            {
92
                _token = value;
93
                _baseClient.Headers["X-Auth-Token"] = value;
94
            }
95
        }
96

    
97
        //The client also receives a StorageUrl after authentication. All subsequent operations must
98
        //use this url
99
        public Uri StorageUrl { get; set; }
100

    
101

    
102
        public Uri RootAddressUri { get; set; }
103

    
104
       /* private WebProxy _proxy;
105
        public WebProxy Proxy
106
        {
107
            get { return _proxy; }
108
            set
109
            {
110
                _proxy = value;
111
                if (_baseClient != null)
112
                    _baseClient.Proxy = value;                
113
            }
114
        }
115
*/
116

    
117
        /* private Uri _proxy;
118
        public Uri Proxy
119
        {
120
            get { return _proxy; }
121
            set
122
            {
123
                _proxy = value;
124
                if (_baseClient != null)
125
                    _baseClient.Proxy = new WebProxy(value);                
126
            }
127
        }*/
128

    
129
        public double DownloadPercentLimit { get; set; }
130
        public double UploadPercentLimit { get; set; }
131

    
132
        public string AuthenticationUrl { get; set; }
133

    
134
 
135
        public string VersionPath
136
        {
137
            get { return UsePithos ? "v1" : "v1.0"; }
138
        }
139

    
140
        public bool UsePithos { get; set; }
141

    
142

    
143

    
144
        public CloudFilesClient(string userName, string apiKey)
145
        {
146
            UserName = userName;
147
            ApiKey = apiKey;
148
        }
149

    
150
        public CloudFilesClient(AccountInfo accountInfo)
151
        {
152
            if (accountInfo==null)
153
                throw new ArgumentNullException("accountInfo");
154
            Contract.Ensures(!String.IsNullOrWhiteSpace(Token));
155
            Contract.Ensures(StorageUrl != null);
156
            Contract.Ensures(_baseClient != null);
157
            Contract.Ensures(RootAddressUri != null);
158
            Contract.EndContractBlock();          
159

    
160
            _baseClient = new RestClient
161
            {
162
                BaseAddress = accountInfo.StorageUri.ToString(),
163
                Timeout = 10000,
164
                Retries = 3,
165
            };
166
            StorageUrl = accountInfo.StorageUri;
167
            Token = accountInfo.Token;
168
            UserName = accountInfo.UserName;
169

    
170
            //Get the root address (StorageUrl without the account)
171
            var storageUrl = StorageUrl.AbsoluteUri;
172
            var usernameIndex = storageUrl.LastIndexOf(UserName);
173
            var rootUrl = storageUrl.Substring(0, usernameIndex);
174
            RootAddressUri = new Uri(rootUrl);
175
        }
176

    
177

    
178
        public AccountInfo Authenticate()
179
        {
180
            if (String.IsNullOrWhiteSpace(UserName))
181
                throw new InvalidOperationException("UserName is empty");
182
            if (String.IsNullOrWhiteSpace(ApiKey))
183
                throw new InvalidOperationException("ApiKey is empty");
184
            if (String.IsNullOrWhiteSpace(AuthenticationUrl))
185
                throw new InvalidOperationException("AuthenticationUrl is empty");
186
            Contract.Ensures(!String.IsNullOrWhiteSpace(Token));
187
            Contract.Ensures(StorageUrl != null);
188
            Contract.Ensures(_baseClient != null);
189
            Contract.Ensures(RootAddressUri != null);
190
            Contract.EndContractBlock();
191

    
192

    
193
            Log.InfoFormat("[AUTHENTICATE] Start for {0}", UserName);
194

    
195
            var groups = new List<Group>();
196

    
197
            using (var authClient = new RestClient{BaseAddress=AuthenticationUrl})
198
            {                
199
               /* if (Proxy != null)
200
                    authClient.Proxy = Proxy;*/
201

    
202
                Contract.Assume(authClient.Headers!=null);
203

    
204
                authClient.Headers.Add("X-Auth-User", UserName);
205
                authClient.Headers.Add("X-Auth-Key", ApiKey);
206

    
207
                authClient.DownloadStringWithRetry(VersionPath, 3);
208

    
209
                authClient.AssertStatusOK("Authentication failed");
210

    
211
                var storageUrl = authClient.GetHeaderValue("X-Storage-Url");
212
                if (String.IsNullOrWhiteSpace(storageUrl))
213
                    throw new InvalidOperationException("Failed to obtain storage url");
214
                
215
                _baseClient = new RestClient
216
                {
217
                    BaseAddress = storageUrl,
218
                    Timeout = 10000,
219
                    Retries = 3,
220
                    //Proxy=Proxy
221
                };
222

    
223
                StorageUrl = new Uri(storageUrl);
224
                
225
                //Get the root address (StorageUrl without the account)
226
                var usernameIndex=storageUrl.LastIndexOf(UserName);
227
                var rootUrl = storageUrl.Substring(0, usernameIndex);
228
                RootAddressUri = new Uri(rootUrl);
229
                
230
                var token = authClient.GetHeaderValue("X-Auth-Token");
231
                if (String.IsNullOrWhiteSpace(token))
232
                    throw new InvalidOperationException("Failed to obtain token url");
233
                Token = token;
234

    
235
               /* var keys = authClient.ResponseHeaders.AllKeys.AsQueryable();
236
                groups = (from key in keys
237
                            where key.StartsWith("X-Account-Group-")
238
                            let name = key.Substring(16)
239
                            select new Group(name, authClient.ResponseHeaders[key]))
240
                        .ToList();
241
                    
242
*/
243
            }
244

    
245
            Log.InfoFormat("[AUTHENTICATE] End for {0}", UserName);
246
            Debug.Assert(_baseClient!=null);
247

    
248
            return new AccountInfo {StorageUri = StorageUrl, Token = Token, UserName = UserName,Groups=groups};            
249

    
250
        }
251

    
252

    
253

    
254
        public IList<ContainerInfo> ListContainers(string account)
255
        {
256
            using (var client = new RestClient(_baseClient))
257
            {
258
                if (!String.IsNullOrWhiteSpace(account))
259
                    client.BaseAddress = GetAccountUrl(account);
260
                
261
                client.Parameters.Clear();
262
                client.Parameters.Add("format", "json");
263
                var content = client.DownloadStringWithRetry("", 3);
264
                client.AssertStatusOK("List Containers failed");
265

    
266
                if (client.StatusCode == HttpStatusCode.NoContent)
267
                    return new List<ContainerInfo>();
268
                var infos = JsonConvert.DeserializeObject<IList<ContainerInfo>>(content);
269
                
270
                foreach (var info in infos)
271
                {
272
                    info.Account = account;
273
                }
274
                return infos;
275
            }
276

    
277
        }
278

    
279
        private string GetAccountUrl(string account)
280
        {
281
            return new Uri(RootAddressUri, new Uri(account,UriKind.Relative)).AbsoluteUri;
282
        }
283

    
284
        public IList<ShareAccountInfo> ListSharingAccounts(DateTime? since=null)
285
        {
286
            using (ThreadContext.Stacks["Share"].Push("List Accounts"))
287
            {
288
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
289

    
290
                using (var client = new RestClient(_baseClient))
291
                {
292
                    client.Parameters.Clear();
293
                    client.Parameters.Add("format", "json");
294
                    client.IfModifiedSince = since;
295

    
296
                    //Extract the username from the base address
297
                    client.BaseAddress = RootAddressUri.AbsoluteUri;
298

    
299
                    var content = client.DownloadStringWithRetry(@"", 3);
300

    
301
                    client.AssertStatusOK("ListSharingAccounts failed");
302

    
303
                    //If the result is empty, return an empty list,
304
                    var infos = String.IsNullOrWhiteSpace(content)
305
                                    ? new List<ShareAccountInfo>()
306
                                //Otherwise deserialize the account list into a list of ShareAccountInfos
307
                                    : JsonConvert.DeserializeObject<IList<ShareAccountInfo>>(content);
308

    
309
                    Log.DebugFormat("END");
310
                    return infos;
311
                }
312
            }
313
        }
314

    
315
        //Request listing of all objects in a container modified since a specific time.
316
        //If the *since* value is missing, return all objects
317
        public IList<ObjectInfo> ListSharedObjects(DateTime? since = null)
318
        {
319

    
320
            using (ThreadContext.Stacks["Share"].Push("List Objects"))
321
            {
322
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
323
                //'since' is not used here because we need to have ListObjects return a NoChange result
324
                //for all shared accounts,containers
325
                var accounts = ListSharingAccounts();
326
                var items = from account in accounts 
327
                            let containers = ListContainers(account.name) 
328
                            from container in containers 
329
                            select ListObjects(account.name, container.Name,since);
330
                var objects=items.SelectMany(r=> r).ToList();
331
/*
332
                var objects = new List<ObjectInfo>();
333
                foreach (var containerObjects in items)
334
                {
335
                    objects.AddRange(containerObjects);
336
                }
337
*/
338
                if (Log.IsDebugEnabled) Log.DebugFormat("END");
339
                return objects;
340
            }
341
        }
342

    
343
        public void SetTags(ObjectInfo target,IDictionary<string,string> tags)
344
        {
345
            if (String.IsNullOrWhiteSpace(Token))
346
                throw new InvalidOperationException("The Token is not set");
347
            if (StorageUrl == null)
348
                throw new InvalidOperationException("The StorageUrl is not set");
349
            if (target == null)
350
                throw new ArgumentNullException("target");
351
            Contract.EndContractBlock();
352

    
353
            using (ThreadContext.Stacks["Share"].Push("Share Object"))
354
            {
355
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
356

    
357
                using (var client = new RestClient(_baseClient))
358
                {
359

    
360
                    client.BaseAddress = GetAccountUrl(target.Account);
361

    
362
                    client.Parameters.Clear();
363
                    client.Parameters.Add("update", "");
364

    
365
                    foreach (var tag in tags)
366
                    {
367
                        var headerTag = String.Format("X-Object-Meta-{0}", tag.Key);
368
                        client.Headers.Add(headerTag, tag.Value);
369
                    }
370
                    
371
                    client.DownloadStringWithRetry(target.Container, 3);
372

    
373
                    
374
                    client.AssertStatusOK("SetTags failed");
375
                    //If the status is NOT ACCEPTED we have a problem
376
                    if (client.StatusCode != HttpStatusCode.Accepted)
377
                    {
378
                        Log.Error("Failed to set tags");
379
                        throw new Exception("Failed to set tags");
380
                    }
381

    
382
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
383
                }
384
            }
385

    
386

    
387
        }
388

    
389
        public void ShareObject(string account, string container, string objectName, string shareTo, bool read, bool write)
390
        {
391
            if (String.IsNullOrWhiteSpace(Token))
392
                throw new InvalidOperationException("The Token is not set");
393
            if (StorageUrl==null)
394
                throw new InvalidOperationException("The StorageUrl is not set");
395
            if (String.IsNullOrWhiteSpace(container))
396
                throw new ArgumentNullException("container");
397
            if (String.IsNullOrWhiteSpace(objectName))
398
                throw new ArgumentNullException("objectName");
399
            if (String.IsNullOrWhiteSpace(account))
400
                throw new ArgumentNullException("account");
401
            if (String.IsNullOrWhiteSpace(shareTo))
402
                throw new ArgumentNullException("shareTo");
403
            Contract.EndContractBlock();
404

    
405
            using (ThreadContext.Stacks["Share"].Push("Share Object"))
406
            {
407
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
408
                
409
                using (var client = new RestClient(_baseClient))
410
                {
411

    
412
                    client.BaseAddress = GetAccountUrl(account);
413

    
414
                    client.Parameters.Clear();
415
                    client.Parameters.Add("format", "json");
416

    
417
                    string permission = "";
418
                    if (write)
419
                        permission = String.Format("write={0}", shareTo);
420
                    else if (read)
421
                        permission = String.Format("read={0}", shareTo);
422
                    client.Headers.Add("X-Object-Sharing", permission);
423

    
424
                    var content = client.DownloadStringWithRetry(container, 3);
425

    
426
                    client.AssertStatusOK("ShareObject failed");
427

    
428
                    //If the result is empty, return an empty list,
429
                    var infos = String.IsNullOrWhiteSpace(content)
430
                                    ? new List<ObjectInfo>()
431
                                //Otherwise deserialize the object list into a list of ObjectInfos
432
                                    : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
433

    
434
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
435
                }
436
            }
437

    
438

    
439
        }
440

    
441
        public AccountInfo GetAccountPolicies(AccountInfo accountInfo)
442
        {
443
            if (accountInfo==null)
444
                throw new ArgumentNullException("accountInfo");
445
            Contract.EndContractBlock();
446

    
447
            using (ThreadContext.Stacks["Account"].Push("GetPolicies"))
448
            {
449
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
450

    
451
                using (var client = new RestClient(_baseClient))
452
                {
453
                    if (!String.IsNullOrWhiteSpace(accountInfo.UserName))
454
                        client.BaseAddress = GetAccountUrl(accountInfo.UserName);
455

    
456
                    client.Parameters.Clear();
457
                    client.Parameters.Add("format", "json");                    
458
                    client.Head(String.Empty, 3);
459

    
460
                    var quotaValue=client.ResponseHeaders["X-Account-Policy-Quota"];
461
                    var bytesValue= client.ResponseHeaders["X-Account-Bytes-Used"];
462

    
463
                    long quota, bytes;
464
                    if (long.TryParse(quotaValue, out quota))
465
                        accountInfo.Quota = quota;
466
                    if (long.TryParse(bytesValue, out bytes))
467
                        accountInfo.BytesUsed = bytes;
468
                    
469
                    return accountInfo;
470

    
471
                }
472

    
473
            }
474
        }
475

    
476
        public void UpdateMetadata(ObjectInfo objectInfo)
477
        {
478
            if (objectInfo == null)
479
                throw new ArgumentNullException("objectInfo");
480
            Contract.EndContractBlock();
481

    
482
            using (ThreadContext.Stacks["Objects"].Push("UpdateMetadata"))
483
            {
484
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
485

    
486

    
487
                using(var client=new RestClient(_baseClient))
488
                {
489

    
490
                    client.BaseAddress = GetAccountUrl(objectInfo.Account);
491
                    
492
                    client.Parameters.Clear();
493
                    
494

    
495
                    //Set Tags
496
                    foreach (var tag in objectInfo.Tags)
497
                    {
498
                        var headerTag = String.Format("X-Object-Meta-{0}", tag.Key);
499
                        client.Headers.Add(headerTag, tag.Value);
500
                    }
501

    
502
                    //Set Permissions
503

    
504
                    var permissions=objectInfo.GetPermissionString();
505
                    client.SetNonEmptyHeaderValue("X-Object-Sharing",permissions);
506

    
507
                    client.SetNonEmptyHeaderValue("Content-Disposition",objectInfo.ContendDisposition);
508
                    client.SetNonEmptyHeaderValue("Content-Encoding",objectInfo.ContentEncoding);
509
                    client.SetNonEmptyHeaderValue("X-Object-Manifest",objectInfo.Manifest);
510
                    var isPublic = objectInfo.IsPublic.ToString().ToLower();
511
                    client.Headers.Add("X-Object-Public", isPublic);
512

    
513

    
514
                    /*var uriBuilder = client.GetAddressBuilder(objectInfo.Container, objectInfo.Name);
515
                    uriBuilder.Query = "update=";
516
                    var uri = uriBuilder.Uri.MakeRelativeUri(this.RootAddressUri);*/
517
                    var address = String.Format("{0}/{1}?update=",objectInfo.Container, objectInfo.Name);
518
                    client.PostWithRetry(address,"application/xml");
519
                    
520
                    //client.UploadValues(uri,new NameValueCollection());
521

    
522

    
523
                    client.AssertStatusOK("UpdateMetadata failed");
524
                    //If the status is NOT ACCEPTED or OK we have a problem
525
                    if (!(client.StatusCode == HttpStatusCode.Accepted || client.StatusCode == HttpStatusCode.OK))
526
                    {
527
                        Log.Error("Failed to update metadata");
528
                        throw new Exception("Failed to update metadata");
529
                    }
530

    
531
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
532
                }
533
            }
534

    
535
        }
536

    
537
        public void UpdateMetadata(ContainerInfo containerInfo)
538
        {
539
            if (containerInfo == null)
540
                throw new ArgumentNullException("containerInfo");
541
            Contract.EndContractBlock();
542

    
543
            using (ThreadContext.Stacks["Containers"].Push("UpdateMetadata"))
544
            {
545
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
546

    
547

    
548
                using(var client=new RestClient(_baseClient))
549
                {
550

    
551
                    client.BaseAddress = GetAccountUrl(containerInfo.Account);
552
                    
553
                    client.Parameters.Clear();
554
                    
555

    
556
                    //Set Tags
557
                    foreach (var tag in containerInfo.Tags)
558
                    {
559
                        var headerTag = String.Format("X-Container-Meta-{0}", tag.Key);
560
                        client.Headers.Add(headerTag, tag.Value);
561
                    }
562

    
563
                    
564
                    //Set Policies
565
                    foreach (var policy in containerInfo.Policies)
566
                    {
567
                        var headerPolicy = String.Format("X-Container-Policy-{0}", policy.Key);
568
                        client.Headers.Add(headerPolicy, policy.Value);
569
                    }
570

    
571

    
572
                    var uriBuilder = client.GetAddressBuilder(containerInfo.Name,"");
573
                    var uri = uriBuilder.Uri;
574

    
575
                    client.UploadValues(uri,new NameValueCollection());
576

    
577

    
578
                    client.AssertStatusOK("UpdateMetadata failed");
579
                    //If the status is NOT ACCEPTED or OK we have a problem
580
                    if (!(client.StatusCode == HttpStatusCode.Accepted || client.StatusCode == HttpStatusCode.OK))
581
                    {
582
                        Log.Error("Failed to update metadata");
583
                        throw new Exception("Failed to update metadata");
584
                    }
585

    
586
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
587
                }
588
            }
589

    
590
        }
591

    
592

    
593
        public IList<ObjectInfo> ListObjects(string account, string container, DateTime? since = null)
594
        {
595
            if (String.IsNullOrWhiteSpace(container))
596
                throw new ArgumentNullException("container");
597
            Contract.EndContractBlock();
598

    
599
            using (ThreadContext.Stacks["Objects"].Push("List"))
600
            {
601
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
602

    
603
                using (var client = new RestClient(_baseClient))
604
                {
605
                    if (!String.IsNullOrWhiteSpace(account))
606
                        client.BaseAddress = GetAccountUrl(account);
607

    
608
                    client.Parameters.Clear();
609
                    client.Parameters.Add("format", "json");
610
                    client.IfModifiedSince = since;
611
                    var content = client.DownloadStringWithRetry(container, 3);
612

    
613
                    client.AssertStatusOK("ListObjects failed");
614

    
615
                    if (client.StatusCode==HttpStatusCode.NotModified)
616
                        return new[]{new NoModificationInfo(account,container)};
617
                    //If the result is empty, return an empty list,
618
                    var infos = String.IsNullOrWhiteSpace(content)
619
                                    ? new List<ObjectInfo>()
620
                                //Otherwise deserialize the object list into a list of ObjectInfos
621
                                    : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
622

    
623
                    foreach (var info in infos)
624
                    {
625
                        info.Container = container;
626
                        info.Account = account;
627
                        info.StorageUri = this.StorageUrl;
628
                    }
629
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
630
                    return infos;
631
                }
632
            }
633
        }
634

    
635
        public IList<ObjectInfo> ListObjects(string account, string container, string folder, DateTime? since = null)
636
        {
637
            if (String.IsNullOrWhiteSpace(container))
638
                throw new ArgumentNullException("container");
639
/*
640
            if (String.IsNullOrWhiteSpace(folder))
641
                throw new ArgumentNullException("folder");
642
*/
643
            Contract.EndContractBlock();
644

    
645
            using (ThreadContext.Stacks["Objects"].Push("List"))
646
            {
647
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
648

    
649
                using (var client = new RestClient(_baseClient))
650
                {
651
                    if (!String.IsNullOrWhiteSpace(account))
652
                        client.BaseAddress = GetAccountUrl(account);
653

    
654
                    client.Parameters.Clear();
655
                    client.Parameters.Add("format", "json");
656
                    client.Parameters.Add("path", folder);
657
                    client.IfModifiedSince = since;
658
                    var content = client.DownloadStringWithRetry(container, 3);
659
                    client.AssertStatusOK("ListObjects failed");
660

    
661
                    if (client.StatusCode==HttpStatusCode.NotModified)
662
                        return new[]{new NoModificationInfo(account,container,folder)};
663

    
664
                    var infos = JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
665
                    foreach (var info in infos)
666
                    {
667
                        info.Account = account;
668
                        if (info.Container == null)
669
                            info.Container = container;
670
                        info.StorageUri = this.StorageUrl;
671
                    }
672
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
673
                    return infos;
674
                }
675
            }
676
        }
677

    
678
 
679
        public bool ContainerExists(string account, string container)
680
        {
681
            if (String.IsNullOrWhiteSpace(container))
682
                throw new ArgumentNullException("container", "The container property can't be empty");
683
            Contract.EndContractBlock();
684

    
685
            using (ThreadContext.Stacks["Containters"].Push("Exists"))
686
            {
687
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
688

    
689
                using (var client = new RestClient(_baseClient))
690
                {
691
                    if (!String.IsNullOrWhiteSpace(account))
692
                        client.BaseAddress = GetAccountUrl(account);
693

    
694
                    client.Parameters.Clear();
695
                    client.Head(container, 3);
696
                                        
697
                    bool result;
698
                    switch (client.StatusCode)
699
                    {
700
                        case HttpStatusCode.OK:
701
                        case HttpStatusCode.NoContent:
702
                            result=true;
703
                            break;
704
                        case HttpStatusCode.NotFound:
705
                            result=false;
706
                            break;
707
                        default:
708
                            throw CreateWebException("ContainerExists", client.StatusCode);
709
                    }
710
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
711

    
712
                    return result;
713
                }
714
                
715
            }
716
        }
717

    
718
        public bool ObjectExists(string account, string container, string objectName)
719
        {
720
            if (String.IsNullOrWhiteSpace(container))
721
                throw new ArgumentNullException("container", "The container property can't be empty");
722
            if (String.IsNullOrWhiteSpace(objectName))
723
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
724
            Contract.EndContractBlock();
725

    
726
            using (var client = new RestClient(_baseClient))
727
            {
728
                if (!String.IsNullOrWhiteSpace(account))
729
                    client.BaseAddress = GetAccountUrl(account);
730

    
731
                client.Parameters.Clear();
732
                client.Head(container + "/" + objectName, 3);
733

    
734
                switch (client.StatusCode)
735
                {
736
                    case HttpStatusCode.OK:
737
                    case HttpStatusCode.NoContent:
738
                        return true;
739
                    case HttpStatusCode.NotFound:
740
                        return false;
741
                    default:
742
                        throw CreateWebException("ObjectExists", client.StatusCode);
743
                }
744
            }
745

    
746
        }
747

    
748
        public ObjectInfo GetObjectInfo(string account, string container, string objectName)
749
        {
750
            if (String.IsNullOrWhiteSpace(container))
751
                throw new ArgumentNullException("container", "The container property can't be empty");
752
            if (String.IsNullOrWhiteSpace(objectName))
753
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
754
            Contract.EndContractBlock();
755

    
756
            using (ThreadContext.Stacks["Objects"].Push("GetObjectInfo"))
757
            {                
758

    
759
                using (var client = new RestClient(_baseClient))
760
                {
761
                    if (!String.IsNullOrWhiteSpace(account))
762
                        client.BaseAddress = GetAccountUrl(account);
763
                    try
764
                    {
765
                        client.Parameters.Clear();
766

    
767
                        client.Head(container + "/" + objectName, 3);
768

    
769
                        if (client.TimedOut)
770
                            return ObjectInfo.Empty;
771

    
772
                        switch (client.StatusCode)
773
                        {
774
                            case HttpStatusCode.OK:
775
                            case HttpStatusCode.NoContent:
776
                                var keys = client.ResponseHeaders.AllKeys.AsQueryable();
777
                                var tags = client.GetMeta("X-Object-Meta-");
778
                                var extensions = (from key in keys
779
                                                  where key.StartsWith("X-Object-") && !key.StartsWith("X-Object-Meta-")
780
                                                  select new {Name = key, Value = client.ResponseHeaders[key]})
781
                                    .ToDictionary(t => t.Name, t => t.Value);
782

    
783
                                var permissions=client.GetHeaderValue("X-Object-Sharing", true);
784
                                
785
                                
786
                                var info = new ObjectInfo
787
                                               {
788
                                                   Account = account,
789
                                                   Container = container,
790
                                                   Name = objectName,
791
                                                   ETag = client.GetHeaderValue("ETag"),
792
                                                   X_Object_Hash = client.GetHeaderValue("X-Object-Hash"),
793
                                                   Content_Type = client.GetHeaderValue("Content-Type"),
794
                                                   Bytes = Convert.ToInt64(client.GetHeaderValue("Content-Length",true)),
795
                                                   Tags = tags,
796
                                                   Last_Modified = client.LastModified,
797
                                                   Extensions = extensions,
798
                                                   ContentEncoding=client.GetHeaderValue("Content-Encoding",true),
799
                                                   ContendDisposition = client.GetHeaderValue("Content-Disposition",true),
800
                                                   Manifest=client.GetHeaderValue("X-Object-Manifest",true),
801
                                                   PublicUrl=client.GetHeaderValue("X-Object-Public",true),  
802
                                                   StorageUri=this.StorageUrl,
803
                                               };
804
                                info.SetPermissions(permissions);
805
                                return info;
806
                            case HttpStatusCode.NotFound:
807
                                return ObjectInfo.Empty;
808
                            default:
809
                                throw new WebException(
810
                                    String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
811
                                                  objectName, client.StatusCode));
812
                        }
813

    
814
                    }
815
                    catch (RetryException)
816
                    {
817
                        Log.WarnFormat("[RETRY FAIL] GetObjectInfo for {0} failed.",objectName);
818
                        return ObjectInfo.Empty;
819
                    }
820
                    catch (WebException e)
821
                    {
822
                        Log.Error(
823
                            String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
824
                                          objectName, client.StatusCode), e);
825
                        throw;
826
                    }
827
                }                
828
            }
829

    
830
        }
831

    
832
        public void CreateFolder(string account, string container, string folder)
833
        {
834
            if (String.IsNullOrWhiteSpace(container))
835
                throw new ArgumentNullException("container", "The container property can't be empty");
836
            if (String.IsNullOrWhiteSpace(folder))
837
                throw new ArgumentNullException("folder", "The folder property can't be empty");
838
            Contract.EndContractBlock();
839

    
840
            var folderUrl=String.Format("{0}/{1}",container,folder);
841
            using (var client = new RestClient(_baseClient))
842
            {
843
                if (!String.IsNullOrWhiteSpace(account))
844
                    client.BaseAddress = GetAccountUrl(account);
845

    
846
                client.Parameters.Clear();
847
                client.Headers.Add("Content-Type", @"application/directory");
848
                client.Headers.Add("Content-Length", "0");
849
                client.PutWithRetry(folderUrl, 3);
850

    
851
                if (client.StatusCode != HttpStatusCode.Created && client.StatusCode != HttpStatusCode.Accepted)
852
                    throw CreateWebException("CreateFolder", client.StatusCode);
853
            }
854
        }
855

    
856
     
857

    
858
        public ContainerInfo GetContainerInfo(string account, string container)
859
        {
860
            if (String.IsNullOrWhiteSpace(container))
861
                throw new ArgumentNullException("container", "The container property can't be empty");
862
            Contract.EndContractBlock();
863

    
864
            using (var client = new RestClient(_baseClient))
865
            {
866
                if (!String.IsNullOrWhiteSpace(account))
867
                    client.BaseAddress = GetAccountUrl(account);                
868

    
869
                client.Head(container);
870
                switch (client.StatusCode)
871
                {
872
                    case HttpStatusCode.OK:
873
                    case HttpStatusCode.NoContent:
874
                        var tags = client.GetMeta("X-Container-Meta-");
875
                        var policies = client.GetMeta("X-Container-Policy-");
876

    
877
                        var containerInfo = new ContainerInfo
878
                                                {
879
                                                    Account=account,
880
                                                    Name = container,
881
                                                    StorageUrl=this.StorageUrl.ToString(),
882
                                                    Count =
883
                                                        long.Parse(client.GetHeaderValue("X-Container-Object-Count")),
884
                                                    Bytes = long.Parse(client.GetHeaderValue("X-Container-Bytes-Used")),
885
                                                    BlockHash = client.GetHeaderValue("X-Container-Block-Hash"),
886
                                                    BlockSize=int.Parse(client.GetHeaderValue("X-Container-Block-Size")),
887
                                                    Last_Modified=client.LastModified,
888
                                                    Tags=tags,
889
                                                    Policies=policies
890
                                                };
891
                        
892

    
893
                        return containerInfo;
894
                    case HttpStatusCode.NotFound:
895
                        return ContainerInfo.Empty;
896
                    default:
897
                        throw CreateWebException("GetContainerInfo", client.StatusCode);
898
                }
899
            }
900
        }
901

    
902
        public void CreateContainer(string account, string container)
903
        {
904
            if (String.IsNullOrWhiteSpace(account))
905
                throw new ArgumentNullException("account");
906
            if (String.IsNullOrWhiteSpace(container))
907
                throw new ArgumentNullException("container");
908
            Contract.EndContractBlock();
909

    
910
            using (var client = new RestClient(_baseClient))
911
            {
912
                if (!String.IsNullOrWhiteSpace(account))
913
                    client.BaseAddress = GetAccountUrl(account);
914

    
915
                client.PutWithRetry(container, 3);
916
                var expectedCodes = new[] {HttpStatusCode.Created, HttpStatusCode.Accepted, HttpStatusCode.OK};
917
                if (!expectedCodes.Contains(client.StatusCode))
918
                    throw CreateWebException("CreateContainer", client.StatusCode);
919
            }
920
        }
921

    
922
        public void DeleteContainer(string account, string container)
923
        {
924
            if (String.IsNullOrWhiteSpace(container))
925
                throw new ArgumentNullException("container", "The container property can't be empty");
926
            Contract.EndContractBlock();
927

    
928
            using (var client = new RestClient(_baseClient))
929
            {
930
                if (!String.IsNullOrWhiteSpace(account))
931
                    client.BaseAddress = GetAccountUrl(account);
932

    
933
                client.DeleteWithRetry(container, 3);
934
                var expectedCodes = new[] {HttpStatusCode.NotFound, HttpStatusCode.NoContent};
935
                if (!expectedCodes.Contains(client.StatusCode))
936
                    throw CreateWebException("DeleteContainer", client.StatusCode);
937
            }
938

    
939
        }
940

    
941
        /// <summary>
942
        /// 
943
        /// </summary>
944
        /// <param name="account"></param>
945
        /// <param name="container"></param>
946
        /// <param name="objectName"></param>
947
        /// <param name="fileName"></param>
948
        /// <returns></returns>
949
        /// <remarks>This method should have no timeout or a very long one</remarks>
950
        //Asynchronously download the object specified by *objectName* in a specific *container* to 
951
        // a local file
952
        public async Task GetObject(string account, string container, string objectName, string fileName,CancellationToken cancellationToken)
953
        {
954
            if (String.IsNullOrWhiteSpace(container))
955
                throw new ArgumentNullException("container", "The container property can't be empty");
956
            if (String.IsNullOrWhiteSpace(objectName))
957
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");            
958
            Contract.EndContractBlock();
959

    
960
            try
961
            {
962
                //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
963
                //object to avoid concurrency errors.
964
                //
965
                //Download operations take a long time therefore they have no timeout.
966
                using(var client = new RestClient(_baseClient) { Timeout = 0 })
967
                {
968
                    if (!String.IsNullOrWhiteSpace(account))
969
                        client.BaseAddress = GetAccountUrl(account);
970

    
971
                    //The container and objectName are relative names. They are joined with the client's
972
                    //BaseAddress to create the object's absolute address
973
                    var builder = client.GetAddressBuilder(container, objectName);
974
                    var uri = builder.Uri;
975

    
976
                    //Download progress is reported to the Trace log
977
                    Log.InfoFormat("[GET] START {0}", objectName);
978
                    client.DownloadProgressChanged += (sender, args) =>
979
                                                      Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
980
                                                                     fileName, args.ProgressPercentage,
981
                                                                     args.BytesReceived,
982
                                                                     args.TotalBytesToReceive);
983

    
984
                    
985
                    //Start downloading the object asynchronously
986
                    await client.DownloadFileTaskAsync(uri, fileName,cancellationToken);
987

    
988
                    //Once the download completes
989
                    //Delete the local client object
990
                }
991
                //And report failure or completion
992
            }
993
            catch (Exception exc)
994
            {
995
                Log.ErrorFormat("[GET] FAIL {0} with {1}", objectName, exc);
996
                throw;
997
            }
998

    
999
            Log.InfoFormat("[GET] END {0}", objectName);                                             
1000

    
1001

    
1002
        }
1003

    
1004
        public Task<IList<string>> PutHashMap(string account, string container, string objectName, TreeHash hash)
1005
        {
1006
            if (String.IsNullOrWhiteSpace(container))
1007
                throw new ArgumentNullException("container");
1008
            if (String.IsNullOrWhiteSpace(objectName))
1009
                throw new ArgumentNullException("objectName");
1010
            if (hash==null)
1011
                throw new ArgumentNullException("hash");
1012
            if (String.IsNullOrWhiteSpace(Token))
1013
                throw new InvalidOperationException("Invalid Token");
1014
            if (StorageUrl == null)
1015
                throw new InvalidOperationException("Invalid Storage Url");
1016
            Contract.EndContractBlock();
1017

    
1018

    
1019
            //Don't use a timeout because putting the hashmap may be a long process
1020
            var client = new RestClient(_baseClient) { Timeout = 0 };           
1021
            if (!String.IsNullOrWhiteSpace(account))
1022
                client.BaseAddress = GetAccountUrl(account);
1023

    
1024
            //The container and objectName are relative names. They are joined with the client's
1025
            //BaseAddress to create the object's absolute address
1026
            var builder = client.GetAddressBuilder(container, objectName);
1027
            builder.Query = "format=json&hashmap";
1028
            var uri = builder.Uri;
1029

    
1030

    
1031
            //Send the tree hash as Json to the server            
1032
            client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
1033
            var jsonHash = hash.ToJson();
1034
                        
1035
            client.Headers.Add("ETag",hash.MD5);
1036
            var uploadTask=client.UploadStringTask(uri, "PUT", jsonHash);
1037
            if (Log.IsDebugEnabled)
1038
                Log.DebugFormat("Hashes:\r\n{0}", jsonHash);
1039
            return uploadTask.ContinueWith(t =>
1040
            {
1041

    
1042
                var empty = (IList<string>)new List<string>();
1043
                
1044

    
1045
                //The server will respond either with 201-created if all blocks were already on the server
1046
                if (client.StatusCode == HttpStatusCode.Created)                    
1047
                {
1048
                    //in which case we return an empty hash list
1049
                    return empty;
1050
                }
1051
                //or with a 409-conflict and return the list of missing parts
1052
                //A 409 will cause an exception so we need to check t.IsFaulted to avoid propagating the exception                
1053
                if (t.IsFaulted)
1054
                {
1055
                    var ex = t.Exception.InnerException;
1056
                    var we = ex as WebException;
1057
                    var response = we.Response as HttpWebResponse;
1058
                    if (response!=null && response.StatusCode==HttpStatusCode.Conflict)
1059
                    {
1060
                        //In case of 409 the missing parts will be in the response content                        
1061
                        using (var stream = response.GetResponseStream())
1062
                        using(var reader=stream.GetLoggedReader(Log))
1063
                        {
1064
                            //We used to have to cleanup the content before returning it because it contains
1065
                            //error content after the list of hashes
1066
                            //
1067
                            //As of 30/1/2012, the result is a proper Json array so we don't need to read the content
1068
                            //line by line
1069
                            
1070
                            var serializer = new JsonSerializer();                            
1071
                            serializer.Error += (sender, args) => Log.ErrorFormat("Deserialization error at [{0}] [{1}]", args.ErrorContext.Error, args.ErrorContext.Member);
1072
                            var hashes = (List<string>)serializer.Deserialize(reader, typeof(List<string>));
1073
                            return hashes;
1074
                        }                        
1075
                    }                    
1076
                    //Any other status code is unexpected and the exception should be rethrown
1077
                    Log.LogError(response);
1078
                    throw ex;
1079
                    
1080
                }
1081

    
1082
                //Any other status code is unexpected but there was no exception. We can probably continue processing
1083
                Log.WarnFormat("Unexcpected status code when putting map: {0} - {1}",client.StatusCode,client.StatusDescription);                    
1084
                
1085
                return empty;
1086
            });
1087

    
1088
        }
1089

    
1090

    
1091
        public async Task<byte[]> GetBlock(string account, string container, Uri relativeUrl, long start, long? end, CancellationToken cancellationToken)
1092
        {
1093
            if (String.IsNullOrWhiteSpace(Token))
1094
                throw new InvalidOperationException("Invalid Token");
1095
            if (StorageUrl == null)
1096
                throw new InvalidOperationException("Invalid Storage Url");
1097
            if (String.IsNullOrWhiteSpace(container))
1098
                throw new ArgumentNullException("container");
1099
            if (relativeUrl == null)
1100
                throw new ArgumentNullException("relativeUrl");
1101
            if (end.HasValue && end < 0)
1102
                throw new ArgumentOutOfRangeException("end");
1103
            if (start < 0)
1104
                throw new ArgumentOutOfRangeException("start");
1105
            Contract.EndContractBlock();
1106

    
1107
            //Don't use a timeout because putting the hashmap may be a long process
1108
            using (var client = new RestClient(_baseClient) {Timeout = 0, RangeFrom = start, RangeTo = end})
1109
            {
1110
                if (!String.IsNullOrWhiteSpace(account))
1111
                    client.BaseAddress = GetAccountUrl(account);
1112

    
1113
                var builder = client.GetAddressBuilder(container, relativeUrl.ToString());
1114
                var uri = builder.Uri;
1115
                
1116
                client.DownloadProgressChanged += (sender, args) =>
1117
                                  Log.DebugFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
1118
                                                 uri.Segments.Last(), args.ProgressPercentage,
1119
                                                 args.BytesReceived,
1120
                                                 args.TotalBytesToReceive);
1121

    
1122

    
1123
                var result = await client.DownloadDataTaskAsync(uri, cancellationToken);
1124
                return result;
1125
            }
1126
        }
1127

    
1128

    
1129
        public async Task PostBlock(string account, string container, byte[] block, int offset, int count,CancellationToken token)
1130
        {
1131
            if (String.IsNullOrWhiteSpace(container))
1132
                throw new ArgumentNullException("container");
1133
            if (block == null)
1134
                throw new ArgumentNullException("block");
1135
            if (offset < 0 || offset >= block.Length)
1136
                throw new ArgumentOutOfRangeException("offset");
1137
            if (count < 0 || count > block.Length)
1138
                throw new ArgumentOutOfRangeException("count");
1139
            if (String.IsNullOrWhiteSpace(Token))
1140
                throw new InvalidOperationException("Invalid Token");
1141
            if (StorageUrl == null)
1142
                throw new InvalidOperationException("Invalid Storage Url");                        
1143
            Contract.EndContractBlock();
1144

    
1145

    
1146
            try
1147
            {
1148

    
1149
                //Don't use a timeout because putting the hashmap may be a long process
1150
                using (var client = new RestClient(_baseClient) { Timeout = 0 })
1151
                {
1152
                    if (!String.IsNullOrWhiteSpace(account))
1153
                        client.BaseAddress = GetAccountUrl(account);
1154

    
1155
                    token.Register(client.CancelAsync);
1156

    
1157
                    var builder = client.GetAddressBuilder(container, "");
1158
                    //We are doing an update
1159
                    builder.Query = "update";
1160
                    var uri = builder.Uri;
1161

    
1162
                    client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
1163

    
1164
                    Log.InfoFormat("[BLOCK POST] START");
1165

    
1166
                    client.UploadProgressChanged += (sender, args) =>
1167
                                                    Log.InfoFormat("[BLOCK POST PROGRESS] {0}% {1} of {2}",
1168
                                                                   args.ProgressPercentage, args.BytesSent,
1169
                                                                   args.TotalBytesToSend);
1170
                    client.UploadFileCompleted += (sender, args) =>
1171
                                                  Log.InfoFormat("[BLOCK POST PROGRESS] Completed ");
1172

    
1173
                    var buffer = new byte[count];
1174
                    Buffer.BlockCopy(block, offset, buffer, 0, count);
1175
                    //Send the block
1176
                    await client.UploadDataTaskAsync(uri, "POST", buffer);
1177
                    Log.InfoFormat("[BLOCK POST] END");
1178
                }
1179
            }
1180
            catch (TaskCanceledException )
1181
            {
1182
                Log.Info("Aborting block");
1183
                throw;
1184
            }
1185
            catch (Exception exc)
1186
            {
1187
                Log.ErrorFormat("[BLOCK POST] FAIL with \r{0}", exc);
1188
                throw;
1189
            }
1190
        }
1191

    
1192

    
1193
        public async Task<TreeHash> GetHashMap(string account, string container, string objectName)
1194
        {
1195
            if (String.IsNullOrWhiteSpace(container))
1196
                throw new ArgumentNullException("container");
1197
            if (String.IsNullOrWhiteSpace(objectName))
1198
                throw new ArgumentNullException("objectName");
1199
            if (String.IsNullOrWhiteSpace(Token))
1200
                throw new InvalidOperationException("Invalid Token");
1201
            if (StorageUrl == null)
1202
                throw new InvalidOperationException("Invalid Storage Url");
1203
            Contract.EndContractBlock();
1204

    
1205
            try
1206
            {
1207
                //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
1208
                //object to avoid concurrency errors.
1209
                //
1210
                //Download operations take a long time therefore they have no timeout.
1211
                //TODO: Do they really? this is a hashmap operation, not a download
1212
                
1213
                //Start downloading the object asynchronously
1214
                using (var client = new RestClient(_baseClient) { Timeout = 0 })
1215
                {
1216
                    if (!String.IsNullOrWhiteSpace(account))
1217
                        client.BaseAddress = GetAccountUrl(account);
1218

    
1219
                    //The container and objectName are relative names. They are joined with the client's
1220
                    //BaseAddress to create the object's absolute address
1221
                    var builder = client.GetAddressBuilder(container, objectName);
1222
                    builder.Query = "format=json&hashmap";
1223
                    var uri = builder.Uri;
1224

    
1225

    
1226
                    var json = await client.DownloadStringTaskAsync(uri);
1227
                    var treeHash = TreeHash.Parse(json);
1228
                    Log.InfoFormat("[GET HASH] END {0}", objectName);
1229
                    return treeHash;
1230
                }
1231
            }
1232
            catch (Exception exc)
1233
            {
1234
                Log.ErrorFormat("[GET HASH] END {0} with {1}", objectName, exc);
1235
                throw;
1236
            }
1237

    
1238
        }
1239

    
1240

    
1241
        /// <summary>
1242
        /// 
1243
        /// </summary>
1244
        /// <param name="account"></param>
1245
        /// <param name="container"></param>
1246
        /// <param name="objectName"></param>
1247
        /// <param name="fileName"></param>
1248
        /// <param name="hash">Optional hash value for the file. If no hash is provided, the method calculates a new hash</param>
1249
        /// <remarks>>This method should have no timeout or a very long one</remarks>
1250
        public async Task PutObject(string account, string container, string objectName, string fileName, string hash = null, string contentType = "application/octet-stream")
1251
        {
1252
            if (String.IsNullOrWhiteSpace(container))
1253
                throw new ArgumentNullException("container", "The container property can't be empty");
1254
            if (String.IsNullOrWhiteSpace(objectName))
1255
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
1256
            if (String.IsNullOrWhiteSpace(fileName))
1257
                throw new ArgumentNullException("fileName", "The fileName property can't be empty");
1258
/*
1259
            if (!File.Exists(fileName) && !Directory.Exists(fileName))
1260
                throw new FileNotFoundException("The file or directory does not exist",fileName);
1261
*/
1262
            
1263
            try
1264
            {
1265

    
1266
                using (var client = new RestClient(_baseClient) { Timeout = 0 })
1267
                {
1268
                    if (!String.IsNullOrWhiteSpace(account))
1269
                        client.BaseAddress = GetAccountUrl(account);
1270

    
1271
                    var builder = client.GetAddressBuilder(container, objectName);
1272
                    var uri = builder.Uri;
1273

    
1274
                    string etag = hash ?? CalculateHash(fileName);
1275

    
1276
                    client.Headers.Add("Content-Type", contentType);
1277
                    client.Headers.Add("ETag", etag);
1278

    
1279

    
1280
                    Log.InfoFormat("[PUT] START {0}", objectName);
1281
                    client.UploadProgressChanged += (sender, args) =>
1282
                                                        {
1283
                                                            using (ThreadContext.Stacks["PUT"].Push("Progress"))
1284
                                                            {
1285
                                                                Log.InfoFormat("{0} {1}% {2} of {3}", fileName,
1286
                                                                               args.ProgressPercentage,
1287
                                                                               args.BytesSent, args.TotalBytesToSend);
1288
                                                            }
1289
                                                        };
1290

    
1291
                    client.UploadFileCompleted += (sender, args) =>
1292
                                                      {
1293
                                                          using (ThreadContext.Stacks["PUT"].Push("Progress"))
1294
                                                          {
1295
                                                              Log.InfoFormat("Completed {0}", fileName);
1296
                                                          }
1297
                                                      };                    
1298
                    if (contentType=="application/directory")
1299
                        await client.UploadDataTaskAsync(uri, "PUT", new byte[0]);
1300
                    else
1301
                        await client.UploadFileTaskAsync(uri, "PUT", fileName);
1302
                }
1303

    
1304
                Log.InfoFormat("[PUT] END {0}", objectName);
1305
            }
1306
            catch (Exception exc)
1307
            {
1308
                Log.ErrorFormat("[PUT] END {0} with {1}", objectName, exc);
1309
                throw;
1310
            }                
1311

    
1312
        }
1313
       
1314
        
1315
        private static string CalculateHash(string fileName)
1316
        {
1317
            Contract.Requires(!String.IsNullOrWhiteSpace(fileName));
1318
            Contract.EndContractBlock();
1319

    
1320
            string hash;
1321
            using (var hasher = MD5.Create())
1322
            using(var stream=File.OpenRead(fileName))
1323
            {
1324
                var hashBuilder=new StringBuilder();
1325
                foreach (byte b in hasher.ComputeHash(stream))
1326
                    hashBuilder.Append(b.ToString("x2").ToLower());
1327
                hash = hashBuilder.ToString();                
1328
            }
1329
            return hash;
1330
        }
1331
        
1332
        public void MoveObject(string account, string sourceContainer, string oldObjectName, string targetContainer, string newObjectName)
1333
        {
1334
            if (String.IsNullOrWhiteSpace(sourceContainer))
1335
                throw new ArgumentNullException("sourceContainer", "The container property can't be empty");
1336
            if (String.IsNullOrWhiteSpace(oldObjectName))
1337
                throw new ArgumentNullException("oldObjectName", "The oldObjectName property can't be empty");
1338
            if (String.IsNullOrWhiteSpace(targetContainer))
1339
                throw new ArgumentNullException("targetContainer", "The container property can't be empty");
1340
            if (String.IsNullOrWhiteSpace(newObjectName))
1341
                throw new ArgumentNullException("newObjectName", "The newObjectName property can't be empty");
1342
            Contract.EndContractBlock();
1343

    
1344
            var targetUrl = targetContainer + "/" + newObjectName;
1345
            var sourceUrl = String.Format("/{0}/{1}", sourceContainer, oldObjectName);
1346

    
1347
            using (var client = new RestClient(_baseClient))
1348
            {
1349
                if (!String.IsNullOrWhiteSpace(account))
1350
                    client.BaseAddress = GetAccountUrl(account);
1351

    
1352
                client.Headers.Add("X-Move-From", sourceUrl);
1353
                client.PutWithRetry(targetUrl, 3);
1354

    
1355
                var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created};
1356
                if (!expectedCodes.Contains(client.StatusCode))
1357
                    throw CreateWebException("MoveObject", client.StatusCode);
1358
            }
1359
        }
1360

    
1361
        public void DeleteObject(string account, string sourceContainer, string objectName)
1362
        {            
1363
            if (String.IsNullOrWhiteSpace(sourceContainer))
1364
                throw new ArgumentNullException("sourceContainer", "The container property can't be empty");
1365
            if (String.IsNullOrWhiteSpace(objectName))
1366
                throw new ArgumentNullException("objectName", "The oldObjectName property can't be empty");
1367
            Contract.EndContractBlock();
1368

    
1369
            var targetUrl = FolderConstants.TrashContainer + "/" + objectName;
1370
            var sourceUrl = String.Format("/{0}/{1}", sourceContainer, objectName);
1371

    
1372
            using (var client = new RestClient(_baseClient))
1373
            {
1374
                if (!String.IsNullOrWhiteSpace(account))
1375
                    client.BaseAddress = GetAccountUrl(account);
1376

    
1377
                client.Headers.Add("X-Move-From", sourceUrl);
1378
                client.AllowedStatusCodes.Add(HttpStatusCode.NotFound);
1379
                Log.InfoFormat("[TRASH] [{0}] to [{1}]",sourceUrl,targetUrl);
1380
                client.PutWithRetry(targetUrl, 3);
1381

    
1382
                var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created,HttpStatusCode.NotFound};
1383
                if (!expectedCodes.Contains(client.StatusCode))
1384
                    throw CreateWebException("DeleteObject", client.StatusCode);
1385
            }
1386
        }
1387

    
1388
      
1389
        private static WebException CreateWebException(string operation, HttpStatusCode statusCode)
1390
        {
1391
            return new WebException(String.Format("{0} failed with unexpected status code {1}", operation, statusCode));
1392
        }
1393

    
1394

    
1395
/*
1396
        public IEnumerable<ObjectInfo> ListDirectories(ContainerInfo container)
1397
        {
1398
            var directories=this.ListObjects(container.Account, container.Name, "/");
1399
        }
1400
*/
1401

    
1402
        public bool CanUpload(string account, ObjectInfo cloudFile)
1403
        {
1404
            Contract.Requires(!String.IsNullOrWhiteSpace(account));
1405
            Contract.Requires(cloudFile!=null);
1406

    
1407
            using (var client = new RestClient(_baseClient))
1408
            {
1409
                if (!String.IsNullOrWhiteSpace(account))
1410
                    client.BaseAddress = GetAccountUrl(account);
1411

    
1412

    
1413
                var parts = cloudFile.Name.Split('/');
1414
                var folder = String.Join("/", parts,0,parts.Length-1);
1415

    
1416
                var fileUrl=String.Format("{0}/{1}/{2}.pithos.ignore",cloudFile.Container,folder,Guid.NewGuid());
1417

    
1418
                client.Parameters.Clear();
1419
                try
1420
                {
1421
                    client.PutWithRetry(fileUrl, 3, @"application/octet-stream");
1422

    
1423
                    var expectedCodes = new[] { HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created};
1424
                    var result=(expectedCodes.Contains(client.StatusCode));
1425
                    DeleteObject(account, cloudFile.Container, fileUrl);
1426
                    return result;
1427
                }
1428
                catch
1429
                {
1430
                    return false;
1431
                }
1432
            }
1433
        }
1434
    }
1435

    
1436
    public class ShareAccountInfo
1437
    {
1438
        public DateTime? last_modified { get; set; }
1439
        public string name { get; set; }
1440
    }
1441
}