Statistics
| Branch: | Revision:

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

History | View | Annotate | Download (57.4 kB)

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

    
38

    
39
// **CloudFilesClient** provides a simple client interface to CloudFiles and Pithos
40
//
41
// The class provides methods to upload/download files, delete files, manage containers
42

    
43

    
44
using System;
45
using System.Collections.Generic;
46
using System.Collections.Specialized;
47
using System.ComponentModel.Composition;
48
using System.Diagnostics;
49
using System.Diagnostics.Contracts;
50
using System.IO;
51
using System.Linq;
52
using System.Net;
53
using System.Security.Cryptography;
54
using System.Text;
55
using System.Threading.Tasks;
56
using Newtonsoft.Json;
57
using Pithos.Interfaces;
58
using log4net;
59

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

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

    
89
        //The client also receives a StorageUrl after authentication. All subsequent operations must
90
        //use this url
91
        public Uri StorageUrl { get; set; }
92

    
93

    
94
        protected Uri RootAddressUri { get; set; }
95

    
96
        private Uri _proxy;
97
        public Uri Proxy
98
        {
99
            get { return _proxy; }
100
            set
101
            {
102
                _proxy = value;
103
                if (_baseClient != null)
104
                    _baseClient.Proxy = new WebProxy(value);                
105
            }
106
        }
107

    
108
        public double DownloadPercentLimit { get; set; }
109
        public double UploadPercentLimit { get; set; }
110

    
111
        public string AuthenticationUrl { get; set; }
112

    
113
 
114
        public string VersionPath
115
        {
116
            get { return UsePithos ? "v1" : "v1.0"; }
117
        }
118

    
119
        public bool UsePithos { get; set; }
120

    
121

    
122
        private static readonly ILog Log = LogManager.GetLogger("CloudFilesClient");
123

    
124
        public CloudFilesClient(string userName, string apiKey)
125
        {
126
            UserName = userName;
127
            ApiKey = apiKey;
128
        }
129

    
130
        public CloudFilesClient(AccountInfo accountInfo)
131
        {
132
            if (accountInfo==null)
133
                throw new ArgumentNullException("accountInfo");
134
            Contract.Ensures(!String.IsNullOrWhiteSpace(Token));
135
            Contract.Ensures(StorageUrl != null);
136
            Contract.Ensures(_baseClient != null);
137
            Contract.Ensures(RootAddressUri != null);
138
            Contract.EndContractBlock();
139

    
140
            _baseClient = new RestClient
141
            {
142
                BaseAddress = accountInfo.StorageUri.ToString(),
143
                Timeout = 10000,
144
                Retries = 3
145
            };
146
            StorageUrl = accountInfo.StorageUri;
147
            Token = accountInfo.Token;
148
            UserName = accountInfo.UserName;
149

    
150
            //Get the root address (StorageUrl without the account)
151
            var storageUrl = StorageUrl.AbsoluteUri;
152
            var usernameIndex = storageUrl.LastIndexOf(UserName);
153
            var rootUrl = storageUrl.Substring(0, usernameIndex);
154
            RootAddressUri = new Uri(rootUrl);
155
        }
156

    
157

    
158
        public AccountInfo Authenticate()
159
        {
160
            if (String.IsNullOrWhiteSpace(UserName))
161
                throw new InvalidOperationException("UserName is empty");
162
            if (String.IsNullOrWhiteSpace(ApiKey))
163
                throw new InvalidOperationException("ApiKey is empty");
164
            if (String.IsNullOrWhiteSpace(AuthenticationUrl))
165
                throw new InvalidOperationException("AuthenticationUrl is empty");
166
            Contract.Ensures(!String.IsNullOrWhiteSpace(Token));
167
            Contract.Ensures(StorageUrl != null);
168
            Contract.Ensures(_baseClient != null);
169
            Contract.Ensures(RootAddressUri != null);
170
            Contract.EndContractBlock();
171

    
172

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

    
175
            var groups = new List<Group>();
176

    
177
            using (var authClient = new RestClient{BaseAddress=AuthenticationUrl})
178
            {
179
                if (Proxy != null)
180
                    authClient.Proxy = new WebProxy(Proxy);
181

    
182
                Contract.Assume(authClient.Headers!=null);
183

    
184
                authClient.Headers.Add("X-Auth-User", UserName);
185
                authClient.Headers.Add("X-Auth-Key", ApiKey);
186

    
187
                authClient.DownloadStringWithRetry(VersionPath, 3);
188

    
189
                authClient.AssertStatusOK("Authentication failed");
190

    
191
                var storageUrl = authClient.GetHeaderValue("X-Storage-Url");
192
                if (String.IsNullOrWhiteSpace(storageUrl))
193
                    throw new InvalidOperationException("Failed to obtain storage url");
194
                
195
                _baseClient = new RestClient
196
                {
197
                    BaseAddress = storageUrl,
198
                    Timeout = 10000,
199
                    Retries = 3
200
                };
201

    
202
                StorageUrl = new Uri(storageUrl);
203
                
204
                //Get the root address (StorageUrl without the account)
205
                var usernameIndex=storageUrl.LastIndexOf(UserName);
206
                var rootUrl = storageUrl.Substring(0, usernameIndex);
207
                RootAddressUri = new Uri(rootUrl);
208
                
209
                var token = authClient.GetHeaderValue("X-Auth-Token");
210
                if (String.IsNullOrWhiteSpace(token))
211
                    throw new InvalidOperationException("Failed to obtain token url");
212
                Token = token;
213

    
214
               /* var keys = authClient.ResponseHeaders.AllKeys.AsQueryable();
215
                groups = (from key in keys
216
                            where key.StartsWith("X-Account-Group-")
217
                            let name = key.Substring(16)
218
                            select new Group(name, authClient.ResponseHeaders[key]))
219
                        .ToList();
220
                    
221
*/
222
            }
223

    
224
            Log.InfoFormat("[AUTHENTICATE] End for {0}", UserName);
225
            
226

    
227
            return new AccountInfo {StorageUri = StorageUrl, Token = Token, UserName = UserName,Groups=groups};            
228

    
229
        }
230

    
231

    
232

    
233
        public IList<ContainerInfo> ListContainers(string account)
234
        {
235
            using (var client = new RestClient(_baseClient))
236
            {
237
                if (!String.IsNullOrWhiteSpace(account))
238
                    client.BaseAddress = GetAccountUrl(account);
239
                
240
                client.Parameters.Clear();
241
                client.Parameters.Add("format", "json");
242
                var content = client.DownloadStringWithRetry("", 3);
243
                client.AssertStatusOK("List Containers failed");
244

    
245
                if (client.StatusCode == HttpStatusCode.NoContent)
246
                    return new List<ContainerInfo>();
247
                var infos = JsonConvert.DeserializeObject<IList<ContainerInfo>>(content);
248
                
249
                foreach (var info in infos)
250
                {
251
                    info.Account = account;
252
                }
253
                return infos;
254
            }
255

    
256
        }
257

    
258
        private string GetAccountUrl(string account)
259
        {
260
            return new Uri(RootAddressUri, new Uri(account,UriKind.Relative)).AbsoluteUri;
261
        }
262

    
263
        public IList<ShareAccountInfo> ListSharingAccounts(DateTime? since=null)
264
        {
265
            using (ThreadContext.Stacks["Share"].Push("List Accounts"))
266
            {
267
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
268

    
269
                using (var client = new RestClient(_baseClient))
270
                {
271
                    client.Parameters.Clear();
272
                    client.Parameters.Add("format", "json");
273
                    client.IfModifiedSince = since;
274

    
275
                    //Extract the username from the base address
276
                    client.BaseAddress = RootAddressUri.AbsoluteUri;
277

    
278
                    var content = client.DownloadStringWithRetry(@"", 3);
279

    
280
                    client.AssertStatusOK("ListSharingAccounts failed");
281

    
282
                    //If the result is empty, return an empty list,
283
                    var infos = String.IsNullOrWhiteSpace(content)
284
                                    ? new List<ShareAccountInfo>()
285
                                //Otherwise deserialize the account list into a list of ShareAccountInfos
286
                                    : JsonConvert.DeserializeObject<IList<ShareAccountInfo>>(content);
287

    
288
                    Log.DebugFormat("END");
289
                    return infos;
290
                }
291
            }
292
        }
293

    
294
        //Request listing of all objects in a container modified since a specific time.
295
        //If the *since* value is missing, return all objects
296
        public IList<ObjectInfo> ListSharedObjects(DateTime? since = null)
297
        {
298

    
299
            using (ThreadContext.Stacks["Share"].Push("List Objects"))
300
            {
301
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
302

    
303
                var objects = new List<ObjectInfo>();
304
                var accounts = ListSharingAccounts(since);
305
                foreach (var account in accounts)
306
                {
307
                    var containers = ListContainers(account.name);
308
                    foreach (var container in containers)
309
                    {
310
                        var containerObjects = ListObjects(account.name, container.Name);
311
                        objects.AddRange(containerObjects);
312
                    }
313
                }
314
                if (Log.IsDebugEnabled) Log.DebugFormat("END");
315
                return objects;
316
            }
317
        }
318

    
319
        public void SetTags(ObjectInfo target,IDictionary<string,string> tags)
320
        {
321
            if (String.IsNullOrWhiteSpace(Token))
322
                throw new InvalidOperationException("The Token is not set");
323
            if (StorageUrl == null)
324
                throw new InvalidOperationException("The StorageUrl is not set");
325
            if (target == null)
326
                throw new ArgumentNullException("target");
327
            Contract.EndContractBlock();
328

    
329
            using (ThreadContext.Stacks["Share"].Push("Share Object"))
330
            {
331
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
332

    
333
                using (var client = new RestClient(_baseClient))
334
                {
335

    
336
                    client.BaseAddress = GetAccountUrl(target.Account);
337

    
338
                    client.Parameters.Clear();
339
                    client.Parameters.Add("update", "");
340

    
341
                    foreach (var tag in tags)
342
                    {
343
                        var headerTag = String.Format("X-Object-Meta-{0}", tag.Key);
344
                        client.Headers.Add(headerTag, tag.Value);
345
                    }
346
                    
347
                    client.DownloadStringWithRetry(target.Container, 3);
348

    
349
                    
350
                    client.AssertStatusOK("SetTags failed");
351
                    //If the status is NOT ACCEPTED we have a problem
352
                    if (client.StatusCode != HttpStatusCode.Accepted)
353
                    {
354
                        Log.Error("Failed to set tags");
355
                        throw new Exception("Failed to set tags");
356
                    }
357

    
358
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
359
                }
360
            }
361

    
362

    
363
        }
364

    
365
        public void ShareObject(string account, string container, string objectName, string shareTo, bool read, bool write)
366
        {
367
            if (String.IsNullOrWhiteSpace(Token))
368
                throw new InvalidOperationException("The Token is not set");
369
            if (StorageUrl==null)
370
                throw new InvalidOperationException("The StorageUrl is not set");
371
            if (String.IsNullOrWhiteSpace(container))
372
                throw new ArgumentNullException("container");
373
            if (String.IsNullOrWhiteSpace(objectName))
374
                throw new ArgumentNullException("objectName");
375
            if (String.IsNullOrWhiteSpace(account))
376
                throw new ArgumentNullException("account");
377
            if (String.IsNullOrWhiteSpace(shareTo))
378
                throw new ArgumentNullException("shareTo");
379
            Contract.EndContractBlock();
380

    
381
            using (ThreadContext.Stacks["Share"].Push("Share Object"))
382
            {
383
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
384
                
385
                using (var client = new RestClient(_baseClient))
386
                {
387

    
388
                    client.BaseAddress = GetAccountUrl(account);
389

    
390
                    client.Parameters.Clear();
391
                    client.Parameters.Add("format", "json");
392

    
393
                    string permission = "";
394
                    if (write)
395
                        permission = String.Format("write={0}", shareTo);
396
                    else if (read)
397
                        permission = String.Format("read={0}", shareTo);
398
                    client.Headers.Add("X-Object-Sharing", permission);
399

    
400
                    var content = client.DownloadStringWithRetry(container, 3);
401

    
402
                    client.AssertStatusOK("ShareObject failed");
403

    
404
                    //If the result is empty, return an empty list,
405
                    var infos = String.IsNullOrWhiteSpace(content)
406
                                    ? new List<ObjectInfo>()
407
                                //Otherwise deserialize the object list into a list of ObjectInfos
408
                                    : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
409

    
410
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
411
                }
412
            }
413

    
414

    
415
        }
416

    
417
        public AccountInfo GetAccountPolicies(AccountInfo accountInfo)
418
        {
419
            if (accountInfo==null)
420
                throw new ArgumentNullException("accountInfo");
421
            Contract.EndContractBlock();
422

    
423
            using (ThreadContext.Stacks["Account"].Push("GetPolicies"))
424
            {
425
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
426

    
427
                using (var client = new RestClient(_baseClient))
428
                {
429
                    if (!String.IsNullOrWhiteSpace(accountInfo.UserName))
430
                        client.BaseAddress = GetAccountUrl(accountInfo.UserName);
431

    
432
                    client.Parameters.Clear();
433
                    client.Parameters.Add("format", "json");                    
434
                    client.Head(String.Empty, 3);
435

    
436
                    var quotaValue=client.ResponseHeaders["X-Account-Policy-Quota"];
437
                    var bytesValue= client.ResponseHeaders["X-Account-Bytes-Used"];
438

    
439
                    long quota, bytes;
440
                    if (long.TryParse(quotaValue, out quota))
441
                        accountInfo.Quota = quota;
442
                    if (long.TryParse(bytesValue, out bytes))
443
                        accountInfo.BytesUsed = bytes;
444
                    
445
                    return accountInfo;
446

    
447
                }
448

    
449
            }
450
        }
451

    
452
        public void UpdateMetadata(ObjectInfo objectInfo)
453
        {
454
            if (objectInfo == null)
455
                throw new ArgumentNullException("objectInfo");
456
            Contract.EndContractBlock();
457

    
458
            using (ThreadContext.Stacks["Objects"].Push("UpdateMetadata"))
459
            {
460
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
461

    
462

    
463
                using(var client=new RestClient(_baseClient))
464
                {
465

    
466
                    client.BaseAddress = GetAccountUrl(objectInfo.Account);
467
                    
468
                    client.Parameters.Clear();
469
                    
470

    
471
                    //Set Tags
472
                    foreach (var tag in objectInfo.Tags)
473
                    {
474
                        var headerTag = String.Format("X-Object-Meta-{0}", tag.Key);
475
                        client.Headers.Add(headerTag, tag.Value);
476
                    }
477

    
478
                    //Set Permissions
479

    
480
                    var permissions=objectInfo.GetPermissionString();
481
                    client.SetNonEmptyHeaderValue("X-Object-Sharing",permissions);
482

    
483
                    client.SetNonEmptyHeaderValue("Content-Disposition",objectInfo.ContendDisposition);
484
                    client.SetNonEmptyHeaderValue("Content-Encoding",objectInfo.ContentEncoding);
485
                    client.SetNonEmptyHeaderValue("X-Object-Manifest",objectInfo.Manifest);
486
                    var isPublic = objectInfo.IsPublic.ToString().ToLower();
487
                    client.Headers.Add("X-Object-Public", isPublic);
488

    
489

    
490
                    var uriBuilder = client.GetAddressBuilder(objectInfo.Container, objectInfo.Name);
491
                    var uri = uriBuilder.Uri;
492

    
493
                    client.UploadValues(uri,new NameValueCollection());
494

    
495

    
496
                    client.AssertStatusOK("UpdateMetadata failed");
497
                    //If the status is NOT ACCEPTED or OK we have a problem
498
                    if (!(client.StatusCode == HttpStatusCode.Accepted || client.StatusCode == HttpStatusCode.OK))
499
                    {
500
                        Log.Error("Failed to update metadata");
501
                        throw new Exception("Failed to update metadata");
502
                    }
503

    
504
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
505
                }
506
            }
507

    
508
        }
509

    
510
        public void UpdateMetadata(ContainerInfo containerInfo)
511
        {
512
            if (containerInfo == null)
513
                throw new ArgumentNullException("containerInfo");
514
            Contract.EndContractBlock();
515

    
516
            using (ThreadContext.Stacks["Containers"].Push("UpdateMetadata"))
517
            {
518
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
519

    
520

    
521
                using(var client=new RestClient(_baseClient))
522
                {
523

    
524
                    client.BaseAddress = GetAccountUrl(containerInfo.Account);
525
                    
526
                    client.Parameters.Clear();
527
                    
528

    
529
                    //Set Tags
530
                    foreach (var tag in containerInfo.Tags)
531
                    {
532
                        var headerTag = String.Format("X-Container-Meta-{0}", tag.Key);
533
                        client.Headers.Add(headerTag, tag.Value);
534
                    }
535

    
536
                    
537
                    //Set Policies
538
                    foreach (var policy in containerInfo.Policies)
539
                    {
540
                        var headerPolicy = String.Format("X-Container-Policy-{0}", policy.Key);
541
                        client.Headers.Add(headerPolicy, policy.Value);
542
                    }
543

    
544

    
545
                    var uriBuilder = client.GetAddressBuilder(containerInfo.Name,"");
546
                    var uri = uriBuilder.Uri;
547

    
548
                    client.UploadValues(uri,new NameValueCollection());
549

    
550

    
551
                    client.AssertStatusOK("UpdateMetadata failed");
552
                    //If the status is NOT ACCEPTED or OK we have a problem
553
                    if (!(client.StatusCode == HttpStatusCode.Accepted || client.StatusCode == HttpStatusCode.OK))
554
                    {
555
                        Log.Error("Failed to update metadata");
556
                        throw new Exception("Failed to update metadata");
557
                    }
558

    
559
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
560
                }
561
            }
562

    
563
        }
564

    
565

    
566
        public IList<ObjectInfo> ListObjects(string account, string container, DateTime? since = null)
567
        {
568
            if (String.IsNullOrWhiteSpace(container))
569
                throw new ArgumentNullException("container");
570
            Contract.EndContractBlock();
571

    
572
            using (ThreadContext.Stacks["Objects"].Push("List"))
573
            {
574
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
575

    
576
                using (var client = new RestClient(_baseClient))
577
                {
578
                    if (!String.IsNullOrWhiteSpace(account))
579
                        client.BaseAddress = GetAccountUrl(account);
580

    
581
                    client.Parameters.Clear();
582
                    client.Parameters.Add("format", "json");
583
                    client.IfModifiedSince = since;
584
                    var content = client.DownloadStringWithRetry(container, 3);
585

    
586
                    client.AssertStatusOK("ListObjects failed");
587

    
588
                    //If the result is empty, return an empty list,
589
                    var infos = String.IsNullOrWhiteSpace(content)
590
                                    ? new List<ObjectInfo>()
591
                                //Otherwise deserialize the object list into a list of ObjectInfos
592
                                    : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
593

    
594
                    foreach (var info in infos)
595
                    {
596
                        info.Container = container;
597
                        info.Account = account;
598
                    }
599
                    if (Log.IsDebugEnabled) Log.DebugFormat("START");
600
                    return infos;
601
                }
602
            }
603
        }
604

    
605

    
606

    
607
        public IList<ObjectInfo> ListObjects(string account, string container, string folder, DateTime? since = null)
608
        {
609
            if (String.IsNullOrWhiteSpace(container))
610
                throw new ArgumentNullException("container");
611
            if (String.IsNullOrWhiteSpace(folder))
612
                throw new ArgumentNullException("folder");
613
            Contract.EndContractBlock();
614

    
615
            using (ThreadContext.Stacks["Objects"].Push("List"))
616
            {
617
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
618

    
619
                using (var client = new RestClient(_baseClient))
620
                {
621
                    if (!String.IsNullOrWhiteSpace(account))
622
                        client.BaseAddress = GetAccountUrl(account);
623

    
624
                    client.Parameters.Clear();
625
                    client.Parameters.Add("format", "json");
626
                    client.Parameters.Add("path", folder);
627
                    client.IfModifiedSince = since;
628
                    var content = client.DownloadStringWithRetry(container, 3);
629
                    client.AssertStatusOK("ListObjects failed");
630

    
631
                    var infos = JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
632

    
633
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
634
                    return infos;
635
                }
636
            }
637
        }
638

    
639
 
640
        public bool ContainerExists(string account, string container)
641
        {
642
            if (String.IsNullOrWhiteSpace(container))
643
                throw new ArgumentNullException("container", "The container property can't be empty");
644
            Contract.EndContractBlock();
645

    
646
            using (ThreadContext.Stacks["Containters"].Push("Exists"))
647
            {
648
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
649

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

    
655
                    client.Parameters.Clear();
656
                    client.Head(container, 3);
657
                                        
658
                    bool result;
659
                    switch (client.StatusCode)
660
                    {
661
                        case HttpStatusCode.OK:
662
                        case HttpStatusCode.NoContent:
663
                            result=true;
664
                            break;
665
                        case HttpStatusCode.NotFound:
666
                            result=false;
667
                            break;
668
                        default:
669
                            throw CreateWebException("ContainerExists", client.StatusCode);
670
                    }
671
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
672

    
673
                    return result;
674
                }
675
                
676
            }
677
        }
678

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

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

    
692
                client.Parameters.Clear();
693
                client.Head(container + "/" + objectName, 3);
694

    
695
                switch (client.StatusCode)
696
                {
697
                    case HttpStatusCode.OK:
698
                    case HttpStatusCode.NoContent:
699
                        return true;
700
                    case HttpStatusCode.NotFound:
701
                        return false;
702
                    default:
703
                        throw CreateWebException("ObjectExists", client.StatusCode);
704
                }
705
            }
706

    
707
        }
708

    
709
        public ObjectInfo GetObjectInfo(string account, string container, string objectName)
710
        {
711
            if (String.IsNullOrWhiteSpace(container))
712
                throw new ArgumentNullException("container", "The container property can't be empty");
713
            if (String.IsNullOrWhiteSpace(objectName))
714
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
715
            Contract.EndContractBlock();
716

    
717
            using (ThreadContext.Stacks["Objects"].Push("GetObjectInfo"))
718
            {                
719

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

    
728
                        client.Head(container + "/" + objectName, 3);
729

    
730
                        if (client.TimedOut)
731
                            return ObjectInfo.Empty;
732

    
733
                        switch (client.StatusCode)
734
                        {
735
                            case HttpStatusCode.OK:
736
                            case HttpStatusCode.NoContent:
737
                                var keys = client.ResponseHeaders.AllKeys.AsQueryable();
738
                                var tags = client.GetMeta("X-Object-Meta-");
739
                                var extensions = (from key in keys
740
                                                  where key.StartsWith("X-Object-") && !key.StartsWith("X-Object-Meta-")
741
                                                  select new {Name = key, Value = client.ResponseHeaders[key]})
742
                                    .ToDictionary(t => t.Name, t => t.Value);
743

    
744
                                var permissions=client.GetHeaderValue("X-Object-Sharing", true);
745
                                
746
                                
747
                                var info = new ObjectInfo
748
                                               {
749
                                                   Account = account,
750
                                                   Container = container,
751
                                                   Name = objectName,
752
                                                   Hash = client.GetHeaderValue("ETag"),
753
                                                   Content_Type = client.GetHeaderValue("Content-Type"),
754
                                                   Bytes = Convert.ToInt64(client.GetHeaderValue("Content-Length",true)),
755
                                                   Tags = tags,
756
                                                   Last_Modified = client.LastModified,
757
                                                   Extensions = extensions,
758
                                                   ContentEncoding=client.GetHeaderValue("Content-Encoding",true),
759
                                                   ContendDisposition = client.GetHeaderValue("Content-Disposition",true),
760
                                                   Manifest=client.GetHeaderValue("X-Object-Manifest",true),
761
                                                   PublicUrl=client.GetHeaderValue("X-Object-Public",true),                                                   
762
                                               };
763
                                info.SetPermissions(permissions);
764
                                return info;
765
                            case HttpStatusCode.NotFound:
766
                                return ObjectInfo.Empty;
767
                            default:
768
                                throw new WebException(
769
                                    String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
770
                                                  objectName, client.StatusCode));
771
                        }
772

    
773
                    }
774
                    catch (RetryException)
775
                    {
776
                        Log.WarnFormat("[RETRY FAIL] GetObjectInfo for {0} failed.",objectName);
777
                        return ObjectInfo.Empty;
778
                    }
779
                    catch (WebException e)
780
                    {
781
                        Log.Error(
782
                            String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
783
                                          objectName, client.StatusCode), e);
784
                        throw;
785
                    }
786
                }                
787
            }
788

    
789
        }
790

    
791
        public void CreateFolder(string account, string container, string folder)
792
        {
793
            if (String.IsNullOrWhiteSpace(container))
794
                throw new ArgumentNullException("container", "The container property can't be empty");
795
            if (String.IsNullOrWhiteSpace(folder))
796
                throw new ArgumentNullException("folder", "The folder property can't be empty");
797
            Contract.EndContractBlock();
798

    
799
            var folderUrl=String.Format("{0}/{1}",container,folder);
800
            using (var client = new RestClient(_baseClient))
801
            {
802
                if (!String.IsNullOrWhiteSpace(account))
803
                    client.BaseAddress = GetAccountUrl(account);
804

    
805
                client.Parameters.Clear();
806
                client.Headers.Add("Content-Type", @"application/directory");
807
                client.Headers.Add("Content-Length", "0");
808
                client.PutWithRetry(folderUrl, 3);
809

    
810
                if (client.StatusCode != HttpStatusCode.Created && client.StatusCode != HttpStatusCode.Accepted)
811
                    throw CreateWebException("CreateFolder", client.StatusCode);
812
            }
813
        }
814

    
815
     
816

    
817
        public ContainerInfo GetContainerInfo(string account, string container)
818
        {
819
            if (String.IsNullOrWhiteSpace(container))
820
                throw new ArgumentNullException("container", "The container property can't be empty");
821
            Contract.EndContractBlock();
822

    
823
            using (var client = new RestClient(_baseClient))
824
            {
825
                if (!String.IsNullOrWhiteSpace(account))
826
                    client.BaseAddress = GetAccountUrl(account);                
827

    
828
                client.Head(container);
829
                switch (client.StatusCode)
830
                {
831
                    case HttpStatusCode.OK:
832
                    case HttpStatusCode.NoContent:
833
                        var tags = client.GetMeta("X-Container-Meta-");
834
                        var policies = client.GetMeta("X-Container-Policy-");
835

    
836
                        var containerInfo = new ContainerInfo
837
                                                {
838
                                                    Account=account,
839
                                                    Name = container,
840
                                                    Count =
841
                                                        long.Parse(client.GetHeaderValue("X-Container-Object-Count")),
842
                                                    Bytes = long.Parse(client.GetHeaderValue("X-Container-Bytes-Used")),
843
                                                    BlockHash = client.GetHeaderValue("X-Container-Block-Hash"),
844
                                                    BlockSize=int.Parse(client.GetHeaderValue("X-Container-Block-Size")),
845
                                                    Last_Modified=client.LastModified,
846
                                                    Tags=tags,
847
                                                    Policies=policies
848
                                                };
849
                        
850

    
851
                        return containerInfo;
852
                    case HttpStatusCode.NotFound:
853
                        return ContainerInfo.Empty;
854
                    default:
855
                        throw CreateWebException("GetContainerInfo", client.StatusCode);
856
                }
857
            }
858
        }
859

    
860
        public void CreateContainer(string account, string container)
861
        {
862
            if (String.IsNullOrWhiteSpace(account))
863
                throw new ArgumentNullException("account");
864
            if (String.IsNullOrWhiteSpace(container))
865
                throw new ArgumentNullException("container");
866
            Contract.EndContractBlock();
867

    
868
            using (var client = new RestClient(_baseClient))
869
            {
870
                if (!String.IsNullOrWhiteSpace(account))
871
                    client.BaseAddress = GetAccountUrl(account);
872

    
873
                client.PutWithRetry(container, 3);
874
                var expectedCodes = new[] {HttpStatusCode.Created, HttpStatusCode.Accepted, HttpStatusCode.OK};
875
                if (!expectedCodes.Contains(client.StatusCode))
876
                    throw CreateWebException("CreateContainer", client.StatusCode);
877
            }
878
        }
879

    
880
        public void DeleteContainer(string account, string container)
881
        {
882
            if (String.IsNullOrWhiteSpace(container))
883
                throw new ArgumentNullException("container", "The container property can't be empty");
884
            Contract.EndContractBlock();
885

    
886
            using (var client = new RestClient(_baseClient))
887
            {
888
                if (!String.IsNullOrWhiteSpace(account))
889
                    client.BaseAddress = GetAccountUrl(account);
890

    
891
                client.DeleteWithRetry(container, 3);
892
                var expectedCodes = new[] {HttpStatusCode.NotFound, HttpStatusCode.NoContent};
893
                if (!expectedCodes.Contains(client.StatusCode))
894
                    throw CreateWebException("DeleteContainer", client.StatusCode);
895
            }
896

    
897
        }
898

    
899
        /// <summary>
900
        /// 
901
        /// </summary>
902
        /// <param name="account"></param>
903
        /// <param name="container"></param>
904
        /// <param name="objectName"></param>
905
        /// <param name="fileName"></param>
906
        /// <returns></returns>
907
        /// <remarks>This method should have no timeout or a very long one</remarks>
908
        //Asynchronously download the object specified by *objectName* in a specific *container* to 
909
        // a local file
910
        public Task GetObject(string account, string container, string objectName, string fileName)
911
        {
912
            if (String.IsNullOrWhiteSpace(container))
913
                throw new ArgumentNullException("container", "The container property can't be empty");
914
            if (String.IsNullOrWhiteSpace(objectName))
915
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");            
916
            Contract.EndContractBlock();
917

    
918
            try
919
            {
920
                //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
921
                //object to avoid concurrency errors.
922
                //
923
                //Download operations take a long time therefore they have no timeout.
924
                var client = new RestClient(_baseClient) { Timeout = 0 };
925
                if (!String.IsNullOrWhiteSpace(account))
926
                    client.BaseAddress = GetAccountUrl(account);
927

    
928
                //The container and objectName are relative names. They are joined with the client's
929
                //BaseAddress to create the object's absolute address
930
                var builder = client.GetAddressBuilder(container, objectName);
931
                var uri = builder.Uri;
932

    
933
                //Download progress is reported to the Trace log
934
                Log.InfoFormat("[GET] START {0}", objectName);
935
                client.DownloadProgressChanged += (sender, args) => 
936
                    Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
937
                                    fileName, args.ProgressPercentage,
938
                                    args.BytesReceived,
939
                                    args.TotalBytesToReceive);                                
940

    
941

    
942
                //Start downloading the object asynchronously
943
                var downloadTask = client.DownloadFileTask(uri, fileName);
944
                
945
                //Once the download completes
946
                return downloadTask.ContinueWith(download =>
947
                                      {
948
                                          //Delete the local client object
949
                                          client.Dispose();
950
                                          //And report failure or completion
951
                                          if (download.IsFaulted)
952
                                          {
953
                                              Log.ErrorFormat("[GET] FAIL for {0} with \r{1}", objectName,
954
                                                               download.Exception);
955
                                          }
956
                                          else
957
                                          {
958
                                              Log.InfoFormat("[GET] END {0}", objectName);                                             
959
                                          }
960
                                      });
961
            }
962
            catch (Exception exc)
963
            {
964
                Log.ErrorFormat("[GET] END {0} with {1}", objectName, exc);
965
                throw;
966
            }
967

    
968

    
969

    
970
        }
971

    
972
        public Task<IList<string>> PutHashMap(string account, string container, string objectName, TreeHash hash)
973
        {
974
            if (String.IsNullOrWhiteSpace(container))
975
                throw new ArgumentNullException("container");
976
            if (String.IsNullOrWhiteSpace(objectName))
977
                throw new ArgumentNullException("objectName");
978
            if (hash==null)
979
                throw new ArgumentNullException("hash");
980
            if (String.IsNullOrWhiteSpace(Token))
981
                throw new InvalidOperationException("Invalid Token");
982
            if (StorageUrl == null)
983
                throw new InvalidOperationException("Invalid Storage Url");
984
            Contract.EndContractBlock();
985

    
986

    
987
            //Don't use a timeout because putting the hashmap may be a long process
988
            var client = new RestClient(_baseClient) { Timeout = 0 };           
989
            if (!String.IsNullOrWhiteSpace(account))
990
                client.BaseAddress = GetAccountUrl(account);
991

    
992
            //The container and objectName are relative names. They are joined with the client's
993
            //BaseAddress to create the object's absolute address
994
            var builder = client.GetAddressBuilder(container, objectName);
995
            builder.Query = "format=json&hashmap";
996
            var uri = builder.Uri;
997

    
998

    
999
            //Send the tree hash as Json to the server            
1000
            client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
1001
            var jsonHash = hash.ToJson();
1002
            var uploadTask=client.UploadStringTask(uri, "PUT", jsonHash);
1003
            
1004
            return uploadTask.ContinueWith(t =>
1005
            {
1006

    
1007
                var empty = (IList<string>)new List<string>();
1008
                
1009

    
1010
                //The server will respond either with 201-created if all blocks were already on the server
1011
                if (client.StatusCode == HttpStatusCode.Created)                    
1012
                {
1013
                    //in which case we return an empty hash list
1014
                    return empty;
1015
                }
1016
                //or with a 409-conflict and return the list of missing parts
1017
                //A 409 will cause an exception so we need to check t.IsFaulted to avoid propagating the exception                
1018
                if (t.IsFaulted)
1019
                {
1020
                    var ex = t.Exception.InnerException;
1021
                    var we = ex as WebException;
1022
                    var response = we.Response as HttpWebResponse;
1023
                    if (response!=null && response.StatusCode==HttpStatusCode.Conflict)
1024
                    {
1025
                        //In case of 409 the missing parts will be in the response content                        
1026
                        using (var stream = response.GetResponseStream())
1027
                        using(var reader=new StreamReader(stream))
1028
                        {
1029
                            Debug.Assert(stream.Position == 0);
1030
                            //We need to cleanup the content before returning it because it contains
1031
                            //error content after the list of hashes
1032
                            var hashes = new List<string>();
1033
                            string line=null;
1034
                            //All lines up to the first empty line are hashes
1035
                            while(!String.IsNullOrWhiteSpace(line=reader.ReadLine()))
1036
                            {
1037
                                hashes.Add(line);
1038
                            }
1039

    
1040
                            return hashes;
1041
                        }                        
1042
                    }                    
1043
                    //Any other status code is unexpected and the exception should be rethrown
1044
                    throw ex;
1045
                    
1046
                }
1047
                //Any other status code is unexpected but there was no exception. We can probably continue processing
1048
                Log.WarnFormat("Unexcpected status code when putting map: {0} - {1}",client.StatusCode,client.StatusDescription);                    
1049
                
1050
                return empty;
1051
            });
1052

    
1053
        }
1054

    
1055
        public Task<byte[]> GetBlock(string account, string container, Uri relativeUrl, long start, long? end)
1056
        {
1057
            if (String.IsNullOrWhiteSpace(Token))
1058
                throw new InvalidOperationException("Invalid Token");
1059
            if (StorageUrl == null)
1060
                throw new InvalidOperationException("Invalid Storage Url");
1061
            if (String.IsNullOrWhiteSpace(container))
1062
                throw new ArgumentNullException("container");
1063
            if (relativeUrl== null)
1064
                throw new ArgumentNullException("relativeUrl");
1065
            if (end.HasValue && end<0)
1066
                throw new ArgumentOutOfRangeException("end");
1067
            if (start<0)
1068
                throw new ArgumentOutOfRangeException("start");
1069
            Contract.EndContractBlock();
1070

    
1071

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

    
1077
            var builder = client.GetAddressBuilder(container, relativeUrl.ToString());
1078
            var uri = builder.Uri;
1079

    
1080
            return client.DownloadDataTask(uri)
1081
                .ContinueWith(t=>
1082
                                  {
1083
                                      client.Dispose();
1084
                                      return t.Result;
1085
                                  });
1086
        }
1087

    
1088

    
1089
        public async Task PostBlock(string account, string container, byte[] block, int offset, int count)
1090
        {
1091
            if (String.IsNullOrWhiteSpace(container))
1092
                throw new ArgumentNullException("container");
1093
            if (block == null)
1094
                throw new ArgumentNullException("block");
1095
            if (offset < 0 || offset >= block.Length)
1096
                throw new ArgumentOutOfRangeException("offset");
1097
            if (count < 0 || count > block.Length)
1098
                throw new ArgumentOutOfRangeException("count");
1099
            if (String.IsNullOrWhiteSpace(Token))
1100
                throw new InvalidOperationException("Invalid Token");
1101
            if (StorageUrl == null)
1102
                throw new InvalidOperationException("Invalid Storage Url");                        
1103
            Contract.EndContractBlock();
1104

    
1105

    
1106
            try
1107
            {
1108

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

    
1115
                    var builder = client.GetAddressBuilder(container, "");
1116
                    //We are doing an update
1117
                    builder.Query = "update";
1118
                    var uri = builder.Uri;
1119

    
1120
                    client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
1121

    
1122
                    Log.InfoFormat("[BLOCK POST] START");
1123

    
1124
                    client.UploadProgressChanged += (sender, args) =>
1125
                                                    Log.InfoFormat("[BLOCK POST PROGRESS] {0}% {1} of {2}",
1126
                                                                   args.ProgressPercentage, args.BytesSent,
1127
                                                                   args.TotalBytesToSend);
1128
                    client.UploadFileCompleted += (sender, args) =>
1129
                                                  Log.InfoFormat("[BLOCK POST PROGRESS] Completed ");
1130

    
1131
                    var buffer = new byte[count];
1132
                    Buffer.BlockCopy(block, offset, buffer, 0, count);
1133
                    //Send the block
1134
                    await client.UploadDataTask(uri, "POST", buffer);
1135
                    Log.InfoFormat("[BLOCK POST] END");
1136
                }
1137
            }
1138
            catch (Exception exc)
1139
            {
1140
                Log.ErrorFormat("[BLOCK POST] FAIL with \r{0}", exc);                                        
1141
                throw;
1142
            }
1143
        }
1144

    
1145

    
1146
        public async Task<TreeHash> GetHashMap(string account, string container, string objectName)
1147
        {
1148
            if (String.IsNullOrWhiteSpace(container))
1149
                throw new ArgumentNullException("container");
1150
            if (String.IsNullOrWhiteSpace(objectName))
1151
                throw new ArgumentNullException("objectName");
1152
            if (String.IsNullOrWhiteSpace(Token))
1153
                throw new InvalidOperationException("Invalid Token");
1154
            if (StorageUrl == null)
1155
                throw new InvalidOperationException("Invalid Storage Url");
1156
            Contract.EndContractBlock();
1157

    
1158
            try
1159
            {
1160
                //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
1161
                //object to avoid concurrency errors.
1162
                //
1163
                //Download operations take a long time therefore they have no timeout.
1164
                //TODO: Do they really? this is a hashmap operation, not a download
1165
                
1166
                //Start downloading the object asynchronously
1167
                using (var client = new RestClient(_baseClient) { Timeout = 0 })
1168
                {
1169
                    if (!String.IsNullOrWhiteSpace(account))
1170
                        client.BaseAddress = GetAccountUrl(account);
1171

    
1172
                    //The container and objectName are relative names. They are joined with the client's
1173
                    //BaseAddress to create the object's absolute address
1174
                    var builder = client.GetAddressBuilder(container, objectName);
1175
                    builder.Query = "format=json&hashmap";
1176
                    var uri = builder.Uri;
1177

    
1178

    
1179
                    var json = await client.DownloadStringTaskAsync(uri);
1180
                    var treeHash = TreeHash.Parse(json);
1181
                    Log.InfoFormat("[GET HASH] END {0}", objectName);
1182
                    return treeHash;
1183
                }
1184
            }
1185
            catch (Exception exc)
1186
            {
1187
                Log.ErrorFormat("[GET HASH] END {0} with {1}", objectName, exc);
1188
                throw;
1189
            }
1190

    
1191
        }
1192

    
1193

    
1194
        /// <summary>
1195
        /// 
1196
        /// </summary>
1197
        /// <param name="account"></param>
1198
        /// <param name="container"></param>
1199
        /// <param name="objectName"></param>
1200
        /// <param name="fileName"></param>
1201
        /// <param name="hash">Optional hash value for the file. If no hash is provided, the method calculates a new hash</param>
1202
        /// <remarks>>This method should have no timeout or a very long one</remarks>
1203
        public async Task PutObject(string account, string container, string objectName, string fileName, string hash = null, string contentType = "application/octet-stream")
1204
        {
1205
            if (String.IsNullOrWhiteSpace(container))
1206
                throw new ArgumentNullException("container", "The container property can't be empty");
1207
            if (String.IsNullOrWhiteSpace(objectName))
1208
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
1209
            if (String.IsNullOrWhiteSpace(fileName))
1210
                throw new ArgumentNullException("fileName", "The fileName property can't be empty");
1211
/*
1212
            if (!File.Exists(fileName) && !Directory.Exists(fileName))
1213
                throw new FileNotFoundException("The file or directory does not exist",fileName);
1214
*/
1215
            Contract.EndContractBlock();
1216
            
1217
            try
1218
            {
1219

    
1220
                using (var client = new RestClient(_baseClient) { Timeout = 0 })
1221
                {
1222
                    if (!String.IsNullOrWhiteSpace(account))
1223
                        client.BaseAddress = GetAccountUrl(account);
1224

    
1225
                    var builder = client.GetAddressBuilder(container, objectName);
1226
                    var uri = builder.Uri;
1227

    
1228
                    string etag = hash ?? CalculateHash(fileName);
1229

    
1230
                    client.Headers.Add("Content-Type", contentType);
1231
                    client.Headers.Add("ETag", etag);
1232

    
1233

    
1234
                    Log.InfoFormat("[PUT] START {0}", objectName);
1235
                    client.UploadProgressChanged += (sender, args) =>
1236
                                                        {
1237
                                                            using (ThreadContext.Stacks["PUT"].Push("Progress"))
1238
                                                            {
1239
                                                                Log.InfoFormat("{0} {1}% {2} of {3}", fileName,
1240
                                                                               args.ProgressPercentage,
1241
                                                                               args.BytesSent, args.TotalBytesToSend);
1242
                                                            }
1243
                                                        };
1244

    
1245
                    client.UploadFileCompleted += (sender, args) =>
1246
                                                      {
1247
                                                          using (ThreadContext.Stacks["PUT"].Push("Progress"))
1248
                                                          {
1249
                                                              Log.InfoFormat("Completed {0}", fileName);
1250
                                                          }
1251
                                                      };
1252
                    if (contentType=="application/directory")
1253
                        await client.UploadDataTaskAsync(uri, "PUT", new byte[0]);
1254
                    else
1255
                        await client.UploadFileTaskAsync(uri, "PUT", fileName);
1256
                }
1257

    
1258
                Log.InfoFormat("[PUT] END {0}", objectName);
1259
            }
1260
            catch (Exception exc)
1261
            {
1262
                Log.ErrorFormat("[PUT] END {0} with {1}", objectName, exc);
1263
                throw;
1264
            }                
1265

    
1266
        }
1267
       
1268
        
1269
        private static string CalculateHash(string fileName)
1270
        {
1271
            Contract.Requires(!String.IsNullOrWhiteSpace(fileName));
1272
            Contract.EndContractBlock();
1273

    
1274
            string hash;
1275
            using (var hasher = MD5.Create())
1276
            using(var stream=File.OpenRead(fileName))
1277
            {
1278
                var hashBuilder=new StringBuilder();
1279
                foreach (byte b in hasher.ComputeHash(stream))
1280
                    hashBuilder.Append(b.ToString("x2").ToLower());
1281
                hash = hashBuilder.ToString();                
1282
            }
1283
            return hash;
1284
        }
1285
        
1286
        public void MoveObject(string account, string sourceContainer, string oldObjectName, string targetContainer, string newObjectName)
1287
        {
1288
            if (String.IsNullOrWhiteSpace(sourceContainer))
1289
                throw new ArgumentNullException("sourceContainer", "The container property can't be empty");
1290
            if (String.IsNullOrWhiteSpace(oldObjectName))
1291
                throw new ArgumentNullException("oldObjectName", "The oldObjectName property can't be empty");
1292
            if (String.IsNullOrWhiteSpace(targetContainer))
1293
                throw new ArgumentNullException("targetContainer", "The container property can't be empty");
1294
            if (String.IsNullOrWhiteSpace(newObjectName))
1295
                throw new ArgumentNullException("newObjectName", "The newObjectName property can't be empty");
1296
            Contract.EndContractBlock();
1297

    
1298
            var targetUrl = targetContainer + "/" + newObjectName;
1299
            var sourceUrl = String.Format("/{0}/{1}", sourceContainer, oldObjectName);
1300

    
1301
            using (var client = new RestClient(_baseClient))
1302
            {
1303
                if (!String.IsNullOrWhiteSpace(account))
1304
                    client.BaseAddress = GetAccountUrl(account);
1305

    
1306
                client.Headers.Add("X-Move-From", sourceUrl);
1307
                client.PutWithRetry(targetUrl, 3);
1308

    
1309
                var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created};
1310
                if (!expectedCodes.Contains(client.StatusCode))
1311
                    throw CreateWebException("MoveObject", client.StatusCode);
1312
            }
1313
        }
1314

    
1315
        public void DeleteObject(string account, string sourceContainer, string objectName)
1316
        {            
1317
            if (String.IsNullOrWhiteSpace(sourceContainer))
1318
                throw new ArgumentNullException("sourceContainer", "The container property can't be empty");
1319
            if (String.IsNullOrWhiteSpace(objectName))
1320
                throw new ArgumentNullException("objectName", "The oldObjectName property can't be empty");
1321
            Contract.EndContractBlock();
1322

    
1323
            var targetUrl = FolderConstants.TrashContainer + "/" + objectName;
1324
            var sourceUrl = String.Format("/{0}/{1}", sourceContainer, objectName);
1325

    
1326
            using (var client = new RestClient(_baseClient))
1327
            {
1328
                if (!String.IsNullOrWhiteSpace(account))
1329
                    client.BaseAddress = GetAccountUrl(account);
1330

    
1331
                client.Headers.Add("X-Move-From", sourceUrl);
1332
                client.AllowedStatusCodes.Add(HttpStatusCode.NotFound);
1333
                client.PutWithRetry(targetUrl, 3);
1334

    
1335
                var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created,HttpStatusCode.NotFound};
1336
                if (!expectedCodes.Contains(client.StatusCode))
1337
                    throw CreateWebException("DeleteObject", client.StatusCode);
1338
            }
1339
        }
1340

    
1341
      
1342
        private static WebException CreateWebException(string operation, HttpStatusCode statusCode)
1343
        {
1344
            return new WebException(String.Format("{0} failed with unexpected status code {1}", operation, statusCode));
1345
        }
1346

    
1347
        
1348
    }
1349

    
1350
    public class ShareAccountInfo
1351
    {
1352
        public DateTime? last_modified { get; set; }
1353
        public string name { get; set; }
1354
    }
1355
}