Statistics
| Branch: | Revision:

root / trunk / Pithos.Network / CloudFilesClient.cs @ 99e6329f

History | View | Annotate | Download (58.9 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;
50
using System.Collections.Generic;
51
using System.Collections.Specialized;
52
using System.ComponentModel.Composition;
53
using System.Diagnostics;
54
using System.Diagnostics.Contracts;
55
using System.IO;
56
using System.Linq;
57
using System.Net;
58
using System.Security.Cryptography;
59
using System.Text;
60
using System.Threading.Tasks;
61
using Newtonsoft.Json;
62
using Pithos.Interfaces;
63
using log4net;
64

    
65
namespace Pithos.Network
66
{
67
    [Export(typeof(ICloudClient))]
68
    public class CloudFilesClient:ICloudClient
69
    {
70
        //CloudFilesClient uses *_baseClient* internally to communicate with the server
71
        //RestClient provides a REST-friendly interface over the standard WebClient.
72
        private RestClient _baseClient;
73
        
74

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

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

    
98

    
99
        protected Uri RootAddressUri { get; set; }
100

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

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

    
126
        public double DownloadPercentLimit { get; set; }
127
        public double UploadPercentLimit { get; set; }
128

    
129
        public string AuthenticationUrl { get; set; }
130

    
131
 
132
        public string VersionPath
133
        {
134
            get { return UsePithos ? "v1" : "v1.0"; }
135
        }
136

    
137
        public bool UsePithos { get; set; }
138

    
139

    
140
        private static readonly ILog Log = LogManager.GetLogger("CloudFilesClient");
141

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

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

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

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

    
175

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

    
190

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

    
193
            var groups = new List<Group>();
194

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

    
200
                Contract.Assume(authClient.Headers!=null);
201

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

    
205
                authClient.DownloadStringWithRetry(VersionPath, 3);
206

    
207
                authClient.AssertStatusOK("Authentication failed");
208

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

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

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

    
243
            Log.InfoFormat("[AUTHENTICATE] End for {0}", UserName);
244
            
245

    
246
            return new AccountInfo {StorageUri = StorageUrl, Token = Token, UserName = UserName,Groups=groups};            
247

    
248
        }
249

    
250

    
251

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

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

    
275
        }
276

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

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

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

    
294
                    //Extract the username from the base address
295
                    client.BaseAddress = RootAddressUri.AbsoluteUri;
296

    
297
                    var content = client.DownloadStringWithRetry(@"", 3);
298

    
299
                    client.AssertStatusOK("ListSharingAccounts failed");
300

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

    
307
                    Log.DebugFormat("END");
308
                    return infos;
309
                }
310
            }
311
        }
312

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

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

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

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

    
355
                using (var client = new RestClient(_baseClient))
356
                {
357

    
358
                    client.BaseAddress = GetAccountUrl(target.Account);
359

    
360
                    client.Parameters.Clear();
361
                    client.Parameters.Add("update", "");
362

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

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

    
380
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
381
                }
382
            }
383

    
384

    
385
        }
386

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

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

    
410
                    client.BaseAddress = GetAccountUrl(account);
411

    
412
                    client.Parameters.Clear();
413
                    client.Parameters.Add("format", "json");
414

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

    
422
                    var content = client.DownloadStringWithRetry(container, 3);
423

    
424
                    client.AssertStatusOK("ShareObject failed");
425

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

    
432
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
433
                }
434
            }
435

    
436

    
437
        }
438

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

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

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

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

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

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

    
469
                }
470

    
471
            }
472
        }
473

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

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

    
484

    
485
                using(var client=new RestClient(_baseClient))
486
                {
487

    
488
                    client.BaseAddress = GetAccountUrl(objectInfo.Account);
489
                    
490
                    client.Parameters.Clear();
491
                    
492

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

    
500
                    //Set Permissions
501

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

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

    
511

    
512
                    var uriBuilder = client.GetAddressBuilder(objectInfo.Container, objectInfo.Name);
513
                    var uri = uriBuilder.Uri;
514

    
515
                    client.UploadValues(uri,new NameValueCollection());
516

    
517

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

    
526
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
527
                }
528
            }
529

    
530
        }
531

    
532
        public void UpdateMetadata(ContainerInfo containerInfo)
533
        {
534
            if (containerInfo == null)
535
                throw new ArgumentNullException("containerInfo");
536
            Contract.EndContractBlock();
537

    
538
            using (ThreadContext.Stacks["Containers"].Push("UpdateMetadata"))
539
            {
540
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
541

    
542

    
543
                using(var client=new RestClient(_baseClient))
544
                {
545

    
546
                    client.BaseAddress = GetAccountUrl(containerInfo.Account);
547
                    
548
                    client.Parameters.Clear();
549
                    
550

    
551
                    //Set Tags
552
                    foreach (var tag in containerInfo.Tags)
553
                    {
554
                        var headerTag = String.Format("X-Container-Meta-{0}", tag.Key);
555
                        client.Headers.Add(headerTag, tag.Value);
556
                    }
557

    
558
                    
559
                    //Set Policies
560
                    foreach (var policy in containerInfo.Policies)
561
                    {
562
                        var headerPolicy = String.Format("X-Container-Policy-{0}", policy.Key);
563
                        client.Headers.Add(headerPolicy, policy.Value);
564
                    }
565

    
566

    
567
                    var uriBuilder = client.GetAddressBuilder(containerInfo.Name,"");
568
                    var uri = uriBuilder.Uri;
569

    
570
                    client.UploadValues(uri,new NameValueCollection());
571

    
572

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

    
581
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
582
                }
583
            }
584

    
585
        }
586

    
587

    
588
        public IList<ObjectInfo> ListObjects(string account, string container, DateTime? since = null)
589
        {
590
            if (String.IsNullOrWhiteSpace(container))
591
                throw new ArgumentNullException("container");
592
            Contract.EndContractBlock();
593

    
594
            using (ThreadContext.Stacks["Objects"].Push("List"))
595
            {
596
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
597

    
598
                using (var client = new RestClient(_baseClient))
599
                {
600
                    if (!String.IsNullOrWhiteSpace(account))
601
                        client.BaseAddress = GetAccountUrl(account);
602

    
603
                    client.Parameters.Clear();
604
                    client.Parameters.Add("format", "json");
605
                    client.IfModifiedSince = since;
606
                    var content = client.DownloadStringWithRetry(container, 3);
607

    
608
                    client.AssertStatusOK("ListObjects failed");
609

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

    
618
                    foreach (var info in infos)
619
                    {
620
                        info.Container = container;
621
                        info.Account = account;
622
                        info.StorageUri = this.StorageUrl;
623
                    }
624
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
625
                    return infos;
626
                }
627
            }
628
        }
629

    
630
        public IList<ObjectInfo> ListObjects(string account, string container, string folder, DateTime? since = null)
631
        {
632
            if (String.IsNullOrWhiteSpace(container))
633
                throw new ArgumentNullException("container");
634
/*
635
            if (String.IsNullOrWhiteSpace(folder))
636
                throw new ArgumentNullException("folder");
637
*/
638
            Contract.EndContractBlock();
639

    
640
            using (ThreadContext.Stacks["Objects"].Push("List"))
641
            {
642
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
643

    
644
                using (var client = new RestClient(_baseClient))
645
                {
646
                    if (!String.IsNullOrWhiteSpace(account))
647
                        client.BaseAddress = GetAccountUrl(account);
648

    
649
                    client.Parameters.Clear();
650
                    client.Parameters.Add("format", "json");
651
                    client.Parameters.Add("path", folder);
652
                    client.IfModifiedSince = since;
653
                    var content = client.DownloadStringWithRetry(container, 3);
654
                    client.AssertStatusOK("ListObjects failed");
655

    
656
                    if (client.StatusCode==HttpStatusCode.NotModified)
657
                        return new[]{new NoModificationInfo(account,container,folder)};
658

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

    
673
 
674
        public bool ContainerExists(string account, string container)
675
        {
676
            if (String.IsNullOrWhiteSpace(container))
677
                throw new ArgumentNullException("container", "The container property can't be empty");
678
            Contract.EndContractBlock();
679

    
680
            using (ThreadContext.Stacks["Containters"].Push("Exists"))
681
            {
682
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
683

    
684
                using (var client = new RestClient(_baseClient))
685
                {
686
                    if (!String.IsNullOrWhiteSpace(account))
687
                        client.BaseAddress = GetAccountUrl(account);
688

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

    
707
                    return result;
708
                }
709
                
710
            }
711
        }
712

    
713
        public bool ObjectExists(string account, string container, string objectName)
714
        {
715
            if (String.IsNullOrWhiteSpace(container))
716
                throw new ArgumentNullException("container", "The container property can't be empty");
717
            if (String.IsNullOrWhiteSpace(objectName))
718
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
719
            Contract.EndContractBlock();
720

    
721
            using (var client = new RestClient(_baseClient))
722
            {
723
                if (!String.IsNullOrWhiteSpace(account))
724
                    client.BaseAddress = GetAccountUrl(account);
725

    
726
                client.Parameters.Clear();
727
                client.Head(container + "/" + objectName, 3);
728

    
729
                switch (client.StatusCode)
730
                {
731
                    case HttpStatusCode.OK:
732
                    case HttpStatusCode.NoContent:
733
                        return true;
734
                    case HttpStatusCode.NotFound:
735
                        return false;
736
                    default:
737
                        throw CreateWebException("ObjectExists", client.StatusCode);
738
                }
739
            }
740

    
741
        }
742

    
743
        public ObjectInfo GetObjectInfo(string account, string container, string objectName)
744
        {
745
            if (String.IsNullOrWhiteSpace(container))
746
                throw new ArgumentNullException("container", "The container property can't be empty");
747
            if (String.IsNullOrWhiteSpace(objectName))
748
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
749
            Contract.EndContractBlock();
750

    
751
            using (ThreadContext.Stacks["Objects"].Push("GetObjectInfo"))
752
            {                
753

    
754
                using (var client = new RestClient(_baseClient))
755
                {
756
                    if (!String.IsNullOrWhiteSpace(account))
757
                        client.BaseAddress = GetAccountUrl(account);
758
                    try
759
                    {
760
                        client.Parameters.Clear();
761

    
762
                        client.Head(container + "/" + objectName, 3);
763

    
764
                        if (client.TimedOut)
765
                            return ObjectInfo.Empty;
766

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

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

    
807
                    }
808
                    catch (RetryException)
809
                    {
810
                        Log.WarnFormat("[RETRY FAIL] GetObjectInfo for {0} failed.",objectName);
811
                        return ObjectInfo.Empty;
812
                    }
813
                    catch (WebException e)
814
                    {
815
                        Log.Error(
816
                            String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
817
                                          objectName, client.StatusCode), e);
818
                        throw;
819
                    }
820
                }                
821
            }
822

    
823
        }
824

    
825
        public void CreateFolder(string account, string container, string folder)
826
        {
827
            if (String.IsNullOrWhiteSpace(container))
828
                throw new ArgumentNullException("container", "The container property can't be empty");
829
            if (String.IsNullOrWhiteSpace(folder))
830
                throw new ArgumentNullException("folder", "The folder property can't be empty");
831
            Contract.EndContractBlock();
832

    
833
            var folderUrl=String.Format("{0}/{1}",container,folder);
834
            using (var client = new RestClient(_baseClient))
835
            {
836
                if (!String.IsNullOrWhiteSpace(account))
837
                    client.BaseAddress = GetAccountUrl(account);
838

    
839
                client.Parameters.Clear();
840
                client.Headers.Add("Content-Type", @"application/directory");
841
                client.Headers.Add("Content-Length", "0");
842
                client.PutWithRetry(folderUrl, 3);
843

    
844
                if (client.StatusCode != HttpStatusCode.Created && client.StatusCode != HttpStatusCode.Accepted)
845
                    throw CreateWebException("CreateFolder", client.StatusCode);
846
            }
847
        }
848

    
849
     
850

    
851
        public ContainerInfo GetContainerInfo(string account, string container)
852
        {
853
            if (String.IsNullOrWhiteSpace(container))
854
                throw new ArgumentNullException("container", "The container property can't be empty");
855
            Contract.EndContractBlock();
856

    
857
            using (var client = new RestClient(_baseClient))
858
            {
859
                if (!String.IsNullOrWhiteSpace(account))
860
                    client.BaseAddress = GetAccountUrl(account);                
861

    
862
                client.Head(container);
863
                switch (client.StatusCode)
864
                {
865
                    case HttpStatusCode.OK:
866
                    case HttpStatusCode.NoContent:
867
                        var tags = client.GetMeta("X-Container-Meta-");
868
                        var policies = client.GetMeta("X-Container-Policy-");
869

    
870
                        var containerInfo = new ContainerInfo
871
                                                {
872
                                                    Account=account,
873
                                                    Name = container,
874
                                                    Count =
875
                                                        long.Parse(client.GetHeaderValue("X-Container-Object-Count")),
876
                                                    Bytes = long.Parse(client.GetHeaderValue("X-Container-Bytes-Used")),
877
                                                    BlockHash = client.GetHeaderValue("X-Container-Block-Hash"),
878
                                                    BlockSize=int.Parse(client.GetHeaderValue("X-Container-Block-Size")),
879
                                                    Last_Modified=client.LastModified,
880
                                                    Tags=tags,
881
                                                    Policies=policies
882
                                                };
883
                        
884

    
885
                        return containerInfo;
886
                    case HttpStatusCode.NotFound:
887
                        return ContainerInfo.Empty;
888
                    default:
889
                        throw CreateWebException("GetContainerInfo", client.StatusCode);
890
                }
891
            }
892
        }
893

    
894
        public void CreateContainer(string account, string container)
895
        {
896
            if (String.IsNullOrWhiteSpace(account))
897
                throw new ArgumentNullException("account");
898
            if (String.IsNullOrWhiteSpace(container))
899
                throw new ArgumentNullException("container");
900
            Contract.EndContractBlock();
901

    
902
            using (var client = new RestClient(_baseClient))
903
            {
904
                if (!String.IsNullOrWhiteSpace(account))
905
                    client.BaseAddress = GetAccountUrl(account);
906

    
907
                client.PutWithRetry(container, 3);
908
                var expectedCodes = new[] {HttpStatusCode.Created, HttpStatusCode.Accepted, HttpStatusCode.OK};
909
                if (!expectedCodes.Contains(client.StatusCode))
910
                    throw CreateWebException("CreateContainer", client.StatusCode);
911
            }
912
        }
913

    
914
        public void DeleteContainer(string account, string container)
915
        {
916
            if (String.IsNullOrWhiteSpace(container))
917
                throw new ArgumentNullException("container", "The container property can't be empty");
918
            Contract.EndContractBlock();
919

    
920
            using (var client = new RestClient(_baseClient))
921
            {
922
                if (!String.IsNullOrWhiteSpace(account))
923
                    client.BaseAddress = GetAccountUrl(account);
924

    
925
                client.DeleteWithRetry(container, 3);
926
                var expectedCodes = new[] {HttpStatusCode.NotFound, HttpStatusCode.NoContent};
927
                if (!expectedCodes.Contains(client.StatusCode))
928
                    throw CreateWebException("DeleteContainer", client.StatusCode);
929
            }
930

    
931
        }
932

    
933
        /// <summary>
934
        /// 
935
        /// </summary>
936
        /// <param name="account"></param>
937
        /// <param name="container"></param>
938
        /// <param name="objectName"></param>
939
        /// <param name="fileName"></param>
940
        /// <returns></returns>
941
        /// <remarks>This method should have no timeout or a very long one</remarks>
942
        //Asynchronously download the object specified by *objectName* in a specific *container* to 
943
        // a local file
944
        public Task GetObject(string account, string container, string objectName, string fileName)
945
        {
946
            if (String.IsNullOrWhiteSpace(container))
947
                throw new ArgumentNullException("container", "The container property can't be empty");
948
            if (String.IsNullOrWhiteSpace(objectName))
949
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");            
950
            Contract.EndContractBlock();
951

    
952
            try
953
            {
954
                //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
955
                //object to avoid concurrency errors.
956
                //
957
                //Download operations take a long time therefore they have no timeout.
958
                var client = new RestClient(_baseClient) { Timeout = 0 };
959
                if (!String.IsNullOrWhiteSpace(account))
960
                    client.BaseAddress = GetAccountUrl(account);
961

    
962
                //The container and objectName are relative names. They are joined with the client's
963
                //BaseAddress to create the object's absolute address
964
                var builder = client.GetAddressBuilder(container, objectName);
965
                var uri = builder.Uri;
966

    
967
                //Download progress is reported to the Trace log
968
                Log.InfoFormat("[GET] START {0}", objectName);
969
                client.DownloadProgressChanged += (sender, args) => 
970
                    Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
971
                                    fileName, args.ProgressPercentage,
972
                                    args.BytesReceived,
973
                                    args.TotalBytesToReceive);                                
974

    
975

    
976
                //Start downloading the object asynchronously
977
                var downloadTask = client.DownloadFileTask(uri, fileName);
978
                
979
                //Once the download completes
980
                return downloadTask.ContinueWith(download =>
981
                                      {
982
                                          //Delete the local client object
983
                                          client.Dispose();
984
                                          //And report failure or completion
985
                                          if (download.IsFaulted)
986
                                          {
987
                                              Log.ErrorFormat("[GET] FAIL for {0} with \r{1}", objectName,
988
                                                               download.Exception);
989
                                          }
990
                                          else
991
                                          {
992
                                              Log.InfoFormat("[GET] END {0}", objectName);                                             
993
                                          }
994
                                      });
995
            }
996
            catch (Exception exc)
997
            {
998
                Log.ErrorFormat("[GET] END {0} with {1}", objectName, exc);
999
                throw;
1000
            }
1001

    
1002

    
1003

    
1004
        }
1005

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

    
1020

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

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

    
1032

    
1033
            //Send the tree hash as Json to the server            
1034
            client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
1035
            var jsonHash = hash.ToJson();
1036
            var uploadTask=client.UploadStringTask(uri, "PUT", jsonHash);
1037
            
1038
            return uploadTask.ContinueWith(t =>
1039
            {
1040

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

    
1044
                //The server will respond either with 201-created if all blocks were already on the server
1045
                if (client.StatusCode == HttpStatusCode.Created)                    
1046
                {
1047
                    //in which case we return an empty hash list
1048
                    return empty;
1049
                }
1050
                //or with a 409-conflict and return the list of missing parts
1051
                //A 409 will cause an exception so we need to check t.IsFaulted to avoid propagating the exception                
1052
                if (t.IsFaulted)
1053
                {
1054
                    var ex = t.Exception.InnerException;
1055
                    var we = ex as WebException;
1056
                    var response = we.Response as HttpWebResponse;
1057
                    if (response!=null && response.StatusCode==HttpStatusCode.Conflict)
1058
                    {
1059
                        //In case of 409 the missing parts will be in the response content                        
1060
                        using (var stream = response.GetResponseStream())
1061
                        using(var reader=new StreamReader(stream))
1062
                        {
1063
                            Debug.Assert(stream.Position == 0);
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
                            var hashes=(List<string>)serializer.Deserialize(reader, typeof (List<string>));
1072

    
1073
                            return hashes;
1074
                        }                        
1075
                    }                    
1076
                    //Any other status code is unexpected and the exception should be rethrown
1077
                    throw ex;
1078
                    
1079
                }
1080
                //Any other status code is unexpected but there was no exception. We can probably continue processing
1081
                Log.WarnFormat("Unexcpected status code when putting map: {0} - {1}",client.StatusCode,client.StatusDescription);                    
1082
                
1083
                return empty;
1084
            });
1085

    
1086
        }
1087

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

    
1104

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

    
1110
            var builder = client.GetAddressBuilder(container, relativeUrl.ToString());
1111
            var uri = builder.Uri;
1112

    
1113
            return client.DownloadDataTask(uri)
1114
                .ContinueWith(t=>
1115
                                  {
1116
                                      client.Dispose();
1117
                                      return t.Result;
1118
                                  });
1119
        }
1120

    
1121

    
1122
        public async Task PostBlock(string account, string container, byte[] block, int offset, int count)
1123
        {
1124
            if (String.IsNullOrWhiteSpace(container))
1125
                throw new ArgumentNullException("container");
1126
            if (block == null)
1127
                throw new ArgumentNullException("block");
1128
            if (offset < 0 || offset >= block.Length)
1129
                throw new ArgumentOutOfRangeException("offset");
1130
            if (count < 0 || count > block.Length)
1131
                throw new ArgumentOutOfRangeException("count");
1132
            if (String.IsNullOrWhiteSpace(Token))
1133
                throw new InvalidOperationException("Invalid Token");
1134
            if (StorageUrl == null)
1135
                throw new InvalidOperationException("Invalid Storage Url");                        
1136
            Contract.EndContractBlock();
1137

    
1138

    
1139
            try
1140
            {
1141

    
1142
            //Don't use a timeout because putting the hashmap may be a long process
1143
                using (var client = new RestClient(_baseClient) { Timeout = 0 })
1144
                {
1145
                    if (!String.IsNullOrWhiteSpace(account))
1146
                        client.BaseAddress = GetAccountUrl(account);
1147

    
1148
                    var builder = client.GetAddressBuilder(container, "");
1149
                    //We are doing an update
1150
                    builder.Query = "update";
1151
                    var uri = builder.Uri;
1152

    
1153
                    client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
1154

    
1155
                    Log.InfoFormat("[BLOCK POST] START");
1156

    
1157
                    client.UploadProgressChanged += (sender, args) =>
1158
                                                    Log.InfoFormat("[BLOCK POST PROGRESS] {0}% {1} of {2}",
1159
                                                                   args.ProgressPercentage, args.BytesSent,
1160
                                                                   args.TotalBytesToSend);
1161
                    client.UploadFileCompleted += (sender, args) =>
1162
                                                  Log.InfoFormat("[BLOCK POST PROGRESS] Completed ");
1163

    
1164
                    var buffer = new byte[count];
1165
                    Buffer.BlockCopy(block, offset, buffer, 0, count);
1166
                    //Send the block
1167
                    await client.UploadDataTask(uri, "POST", buffer);
1168
                    Log.InfoFormat("[BLOCK POST] END");
1169
                }
1170
            }
1171
            catch (Exception exc)
1172
            {
1173
                Log.ErrorFormat("[BLOCK POST] FAIL with \r{0}", exc);                                        
1174
                throw;
1175
            }
1176
        }
1177

    
1178

    
1179
        public async Task<TreeHash> GetHashMap(string account, string container, string objectName)
1180
        {
1181
            if (String.IsNullOrWhiteSpace(container))
1182
                throw new ArgumentNullException("container");
1183
            if (String.IsNullOrWhiteSpace(objectName))
1184
                throw new ArgumentNullException("objectName");
1185
            if (String.IsNullOrWhiteSpace(Token))
1186
                throw new InvalidOperationException("Invalid Token");
1187
            if (StorageUrl == null)
1188
                throw new InvalidOperationException("Invalid Storage Url");
1189
            Contract.EndContractBlock();
1190

    
1191
            try
1192
            {
1193
                //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
1194
                //object to avoid concurrency errors.
1195
                //
1196
                //Download operations take a long time therefore they have no timeout.
1197
                //TODO: Do they really? this is a hashmap operation, not a download
1198
                
1199
                //Start downloading the object asynchronously
1200
                using (var client = new RestClient(_baseClient) { Timeout = 0 })
1201
                {
1202
                    if (!String.IsNullOrWhiteSpace(account))
1203
                        client.BaseAddress = GetAccountUrl(account);
1204

    
1205
                    //The container and objectName are relative names. They are joined with the client's
1206
                    //BaseAddress to create the object's absolute address
1207
                    var builder = client.GetAddressBuilder(container, objectName);
1208
                    builder.Query = "format=json&hashmap";
1209
                    var uri = builder.Uri;
1210

    
1211

    
1212
                    var json = await client.DownloadStringTaskAsync(uri);
1213
                    var treeHash = TreeHash.Parse(json);
1214
                    Log.InfoFormat("[GET HASH] END {0}", objectName);
1215
                    return treeHash;
1216
                }
1217
            }
1218
            catch (Exception exc)
1219
            {
1220
                Log.ErrorFormat("[GET HASH] END {0} with {1}", objectName, exc);
1221
                throw;
1222
            }
1223

    
1224
        }
1225

    
1226

    
1227
        /// <summary>
1228
        /// 
1229
        /// </summary>
1230
        /// <param name="account"></param>
1231
        /// <param name="container"></param>
1232
        /// <param name="objectName"></param>
1233
        /// <param name="fileName"></param>
1234
        /// <param name="hash">Optional hash value for the file. If no hash is provided, the method calculates a new hash</param>
1235
        /// <remarks>>This method should have no timeout or a very long one</remarks>
1236
        public async Task PutObject(string account, string container, string objectName, string fileName, string hash = null, string contentType = "application/octet-stream")
1237
        {
1238
            if (String.IsNullOrWhiteSpace(container))
1239
                throw new ArgumentNullException("container", "The container property can't be empty");
1240
            if (String.IsNullOrWhiteSpace(objectName))
1241
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
1242
            if (String.IsNullOrWhiteSpace(fileName))
1243
                throw new ArgumentNullException("fileName", "The fileName property can't be empty");
1244
/*
1245
            if (!File.Exists(fileName) && !Directory.Exists(fileName))
1246
                throw new FileNotFoundException("The file or directory does not exist",fileName);
1247
*/
1248
            Contract.EndContractBlock();
1249
            
1250
            try
1251
            {
1252

    
1253
                using (var client = new RestClient(_baseClient) { Timeout = 0 })
1254
                {
1255
                    if (!String.IsNullOrWhiteSpace(account))
1256
                        client.BaseAddress = GetAccountUrl(account);
1257

    
1258
                    var builder = client.GetAddressBuilder(container, objectName);
1259
                    var uri = builder.Uri;
1260

    
1261
                    string etag = hash ?? CalculateHash(fileName);
1262

    
1263
                    client.Headers.Add("Content-Type", contentType);
1264
                    client.Headers.Add("ETag", etag);
1265

    
1266

    
1267
                    Log.InfoFormat("[PUT] START {0}", objectName);
1268
                    client.UploadProgressChanged += (sender, args) =>
1269
                                                        {
1270
                                                            using (ThreadContext.Stacks["PUT"].Push("Progress"))
1271
                                                            {
1272
                                                                Log.InfoFormat("{0} {1}% {2} of {3}", fileName,
1273
                                                                               args.ProgressPercentage,
1274
                                                                               args.BytesSent, args.TotalBytesToSend);
1275
                                                            }
1276
                                                        };
1277

    
1278
                    client.UploadFileCompleted += (sender, args) =>
1279
                                                      {
1280
                                                          using (ThreadContext.Stacks["PUT"].Push("Progress"))
1281
                                                          {
1282
                                                              Log.InfoFormat("Completed {0}", fileName);
1283
                                                          }
1284
                                                      };
1285
                    if (contentType=="application/directory")
1286
                        await client.UploadDataTaskAsync(uri, "PUT", new byte[0]);
1287
                    else
1288
                        await client.UploadFileTaskAsync(uri, "PUT", fileName);
1289
                }
1290

    
1291
                Log.InfoFormat("[PUT] END {0}", objectName);
1292
            }
1293
            catch (Exception exc)
1294
            {
1295
                Log.ErrorFormat("[PUT] END {0} with {1}", objectName, exc);
1296
                throw;
1297
            }                
1298

    
1299
        }
1300
       
1301
        
1302
        private static string CalculateHash(string fileName)
1303
        {
1304
            Contract.Requires(!String.IsNullOrWhiteSpace(fileName));
1305
            Contract.EndContractBlock();
1306

    
1307
            string hash;
1308
            using (var hasher = MD5.Create())
1309
            using(var stream=File.OpenRead(fileName))
1310
            {
1311
                var hashBuilder=new StringBuilder();
1312
                foreach (byte b in hasher.ComputeHash(stream))
1313
                    hashBuilder.Append(b.ToString("x2").ToLower());
1314
                hash = hashBuilder.ToString();                
1315
            }
1316
            return hash;
1317
        }
1318
        
1319
        public void MoveObject(string account, string sourceContainer, string oldObjectName, string targetContainer, string newObjectName)
1320
        {
1321
            if (String.IsNullOrWhiteSpace(sourceContainer))
1322
                throw new ArgumentNullException("sourceContainer", "The container property can't be empty");
1323
            if (String.IsNullOrWhiteSpace(oldObjectName))
1324
                throw new ArgumentNullException("oldObjectName", "The oldObjectName property can't be empty");
1325
            if (String.IsNullOrWhiteSpace(targetContainer))
1326
                throw new ArgumentNullException("targetContainer", "The container property can't be empty");
1327
            if (String.IsNullOrWhiteSpace(newObjectName))
1328
                throw new ArgumentNullException("newObjectName", "The newObjectName property can't be empty");
1329
            Contract.EndContractBlock();
1330

    
1331
            var targetUrl = targetContainer + "/" + newObjectName;
1332
            var sourceUrl = String.Format("/{0}/{1}", sourceContainer, oldObjectName);
1333

    
1334
            using (var client = new RestClient(_baseClient))
1335
            {
1336
                if (!String.IsNullOrWhiteSpace(account))
1337
                    client.BaseAddress = GetAccountUrl(account);
1338

    
1339
                client.Headers.Add("X-Move-From", sourceUrl);
1340
                client.PutWithRetry(targetUrl, 3);
1341

    
1342
                var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created};
1343
                if (!expectedCodes.Contains(client.StatusCode))
1344
                    throw CreateWebException("MoveObject", client.StatusCode);
1345
            }
1346
        }
1347

    
1348
        public void DeleteObject(string account, string sourceContainer, string objectName)
1349
        {            
1350
            if (String.IsNullOrWhiteSpace(sourceContainer))
1351
                throw new ArgumentNullException("sourceContainer", "The container property can't be empty");
1352
            if (String.IsNullOrWhiteSpace(objectName))
1353
                throw new ArgumentNullException("objectName", "The oldObjectName property can't be empty");
1354
            Contract.EndContractBlock();
1355

    
1356
            var targetUrl = FolderConstants.TrashContainer + "/" + objectName;
1357
            var sourceUrl = String.Format("/{0}/{1}", sourceContainer, objectName);
1358

    
1359
            using (var client = new RestClient(_baseClient))
1360
            {
1361
                if (!String.IsNullOrWhiteSpace(account))
1362
                    client.BaseAddress = GetAccountUrl(account);
1363

    
1364
                client.Headers.Add("X-Move-From", sourceUrl);
1365
                client.AllowedStatusCodes.Add(HttpStatusCode.NotFound);
1366
                client.PutWithRetry(targetUrl, 3);
1367

    
1368
                var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created,HttpStatusCode.NotFound};
1369
                if (!expectedCodes.Contains(client.StatusCode))
1370
                    throw CreateWebException("DeleteObject", client.StatusCode);
1371
            }
1372
        }
1373

    
1374
      
1375
        private static WebException CreateWebException(string operation, HttpStatusCode statusCode)
1376
        {
1377
            return new WebException(String.Format("{0} failed with unexpected status code {1}", operation, statusCode));
1378
        }
1379

    
1380

    
1381
/*
1382
        public IEnumerable<ObjectInfo> ListDirectories(ContainerInfo container)
1383
        {
1384
            var directories=this.ListObjects(container.Account, container.Name, "/");
1385
        }
1386
*/
1387
    }
1388

    
1389
    public class ShareAccountInfo
1390
    {
1391
        public DateTime? last_modified { get; set; }
1392
        public string name { get; set; }
1393
    }
1394
}