Statistics
| Branch: | Revision:

root / trunk / Pithos.Interfaces / ObjectInfo.cs @ 31c97141

History | View | Annotate | Download (11.2 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="ObjectInfo.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
using System;
43
using System.Collections.Generic;
44
using System.Diagnostics;
45
using System.Diagnostics.Contracts;
46
using System.Dynamic;
47
using System.Globalization;
48
using System.IO;
49
using System.Linq;
50
using System.Text;
51
using Newtonsoft.Json;
52

    
53
namespace Pithos.Interfaces
54
{
55
    [DebuggerDisplay("Name {Name}")]
56
    public class ObjectInfo//:DynamicObject 
57
    {
58
        private readonly List<string> _knownContainers= new List<string>{"trash"};
59
        public string Name { get; set; }
60
        
61
        
62
        public string Hash { get; set; }
63

    
64
        public string X_Object_Hash { get { return Hash; } set { Hash = value; } }
65

    
66
        [JsonProperty("x_object_uuid")]
67
        public string UUID { get; set; }
68

    
69
        public long Bytes { get; set; }
70
        public string Content_Type { get; set; }
71
        public DateTime Last_Modified { get; set; }
72

    
73
        private Dictionary<string, string> _tags=new Dictionary<string, string>();
74
        public Dictionary<string, string> Tags
75
        {
76
            get { return _tags; }
77
            set { _tags = value; }
78
        }
79

    
80
        private Dictionary<string, string> _extensions=new Dictionary<string, string>();
81
        public Dictionary<string, string> Extensions
82
        {
83
            get { return _extensions; }
84
            set
85
            {
86
                _extensions = value;
87
                ExtractKnownExtensions();
88
            }
89
        }
90
        
91
        
92
        private Dictionary<string, string> _permissions=new Dictionary<string, string>();
93
        [JsonProperty("x_object_sharing")]
94
        [JsonConverter(typeof(PermissionConverter))]
95
        public Dictionary<string, string> Permissions
96
        {
97
            get { return _permissions; }
98
            set
99
            {
100
                _permissions = value;                
101
            }
102
        }
103

    
104
        /// <summary>
105
        /// Version number
106
        /// </summary>
107
        [JsonProperty("x_object_version")]
108
        public long? Version { get; set; }
109

    
110

    
111
        /// <summary>
112
        /// Shared object permissions can be Read or Write
113
        /// </summary>
114
        [JsonProperty("x_object_allowed_to")]
115
        public string AllowedTo { get; set; }
116

    
117

    
118
        /// <summary>
119
        /// Version timestamp
120
        /// </summary>
121
        [JsonProperty("X_Object_Version_Timestamp"), JsonConverter(typeof(PithosDateTimeConverter))]
122
        public DateTime? VersionTimestamp { get; set; }
123

    
124
        [JsonProperty("X_Object_Modified_By")]
125
        public string ModifiedBy { get; set; }
126

    
127

    
128
        public Stream Stream { get; set; }
129

    
130

    
131
        public Uri StorageUri { get; set; }
132

    
133
        public string Account { get; set; }
134

    
135
        public string Container { get; set; }
136

    
137
        public Uri Uri
138
        {
139
            get
140
            {
141
                var relativeUrl=String.Format("{0}/{1}/{2}",Account, Container,Name);
142
                return new Uri(StorageUri,relativeUrl);
143
            }
144
        }
145

    
146
        public string ContendDisposition { get; set; }
147

    
148
        public string ContentEncoding { get; set; }
149

    
150
        public string Manifest { get; set; }
151
        
152
        public bool IsPublic
153
        {
154
            get { return !String.IsNullOrWhiteSpace(PublicUrl); }
155
            set
156
            {
157
                if (!value)
158
                    PublicUrl = null;
159
                else if (String.IsNullOrWhiteSpace(PublicUrl))
160
                    PublicUrl="true";                
161
            }
162
        }
163

    
164
        [JsonProperty("X_Object_Public")]
165
        public string PublicUrl { get; set; }
166

    
167
        public string PreviousHash { get; set; }
168

    
169
        public ObjectInfo()
170
        {}
171

    
172
        public ObjectInfo(string accountPath,string accountName,FileSystemInfo fileInfo)
173
        {
174
            if (String.IsNullOrWhiteSpace(accountPath))
175
                throw new ArgumentNullException("accountPath");
176
            if (string.IsNullOrWhiteSpace(accountName))
177
                throw new ArgumentNullException("accountName");
178
            if (fileInfo == null)
179
                throw new ArgumentNullException("fileInfo");
180
            Contract.EndContractBlock();
181

    
182
            var relativeUrl = fileInfo.WithProperCapitalization().AsRelativeUrlTo(accountPath);
183
            //The first part of the URL is the container
184
            var slashIndex = relativeUrl.IndexOf('/');
185
            var container = relativeUrl.Substring(0, slashIndex);
186
            //The second is the file's url relative to the container
187
            var fileUrl = relativeUrl.Substring(slashIndex + 1);
188

    
189
            Account = accountName;
190
            Container = container;
191
            Name = fileUrl; 
192
        }
193

    
194

    
195
        private void ExtractKnownExtensions()
196
        {
197
            Version=GetLong(KnownExtensions.X_Object_Version);
198
            VersionTimestamp = GetTimestamp(KnownExtensions.X_Object_Version_Timestamp);
199
            ModifiedBy = GetString(KnownExtensions.X_Object_Modified_By);
200
        }
201

    
202
        private string GetString(string name)
203
        {            
204
            string value;
205
            _extensions.TryGetValue(name, out value);
206
            return value ;                        
207
        }
208
        
209
        private long? GetLong(string name)
210
        {
211
            string version;
212
            long value;
213
            return _extensions.TryGetValue(name, out version) && long.TryParse(version, out value)
214
                       ? (long?) value
215
                       : null;
216
        }
217

    
218
        private DateTime? GetTimestamp(string name)
219
        {
220
            string version;
221
            DateTime value;
222
            if (_extensions.TryGetValue(name, out version) && 
223
                DateTime.TryParse(version,CultureInfo.InvariantCulture,DateTimeStyles.AdjustToUniversal, out value))
224
            {
225
                return value;
226
            }
227
            return null;
228
        }
229

    
230

    
231
        public static ObjectInfo Empty = new ObjectInfo
232
        {
233
            Name = String.Empty,
234
            Hash = String.Empty,
235
            Bytes = 0,
236
            Content_Type = String.Empty,
237
            Last_Modified = DateTime.MinValue,
238
            Exists=false
239
        };
240

    
241
        private bool _exists=true;
242

    
243
        public bool Exists
244
        {
245
            get {
246
                return _exists;
247
            }
248
            set {
249
                _exists = value;
250
            }
251
        }
252

    
253

    
254
        public string RelativeUrlToFilePath(string currentAccount)
255
        {
256
            if (Name==null)
257
                throw new InvalidOperationException("Name can't be null");
258
            if (String.IsNullOrWhiteSpace(currentAccount))
259
                throw new ArgumentNullException("currentAccount");
260
            Contract.EndContractBlock();
261

    
262
            if (this == Empty)
263
                return String.Empty;
264

    
265
            var unescaped = Uri.UnescapeDataString(Name);
266
            var path = unescaped.Replace("/", "\\");
267
            var pathParts=new Stack<string>();
268
            pathParts.Push(path);
269
            if (!String.IsNullOrWhiteSpace(Container) && !_knownContainers.Contains(Container))
270
                pathParts.Push(Container);
271
            if (!currentAccount.Equals(Account, StringComparison.InvariantCultureIgnoreCase))
272
            {
273
                if (Account != null)
274
                {
275
                    pathParts.Push(Account);
276
                    pathParts.Push(FolderConstants.OthersFolder);
277
                }
278
            }
279
            var finalPath=Path.Combine(pathParts.ToArray());
280
            return finalPath;
281
        }
282

    
283
/*
284
        public override bool TrySetMember(SetMemberBinder binder, object value)
285
        {
286
            if (binder.Name.StartsWith("x_object_meta"))
287
            {
288
                Tags[binder.Name] = value.ToString();
289
            }
290
            return false;
291
        }
292
*/
293

    
294
        public string GetPermissionString()
295
        {
296
            if (Permissions==null)
297
                throw new InvalidOperationException();
298
            Contract.EndContractBlock();
299

    
300
            var permissionBuilder = new StringBuilder();
301
            var groupings = Permissions.GroupBy(pair => pair.Value, pair => pair.Key);
302
            foreach (var grouping in groupings)
303
            {
304
                permissionBuilder.AppendFormat("{0}={1};", grouping.Key, String.Join(",", grouping));
305
            }
306
            var permissions = permissionBuilder.ToString().Trim(';');
307
            return permissions;
308
        }
309

    
310
        public void SetPermissions(string permissions)
311
        {
312
            if (String.IsNullOrWhiteSpace(permissions))
313
                return;
314

    
315
            var permDict=new Dictionary<string, string>();
316
            var perms=permissions.Split(';');
317
            foreach (var perm in perms)
318
            {
319
                var permPairs=perm.Split('=');
320
                var right = permPairs[0];
321
                var users= permPairs[1].Split(new[]{','},StringSplitOptions.RemoveEmptyEntries);
322
                foreach (var user in users)
323
                {
324
                    permDict[user] = right;
325
                }
326
            }
327
            Permissions = permDict;
328
        }
329

    
330
        //The previous values that correspond to a NoModification object
331
        //have the same account, container and possibly the same folder
332
        public bool CorrespondsTo(ObjectInfo other)
333
        {
334
            return other.Account == this.Account
335
                   && other.Container == this.Container
336
                   && (this.Name == null || other.Name.StartsWith(this.Name));
337
        }
338

    
339

    
340
        public ObjectInfo Previous { get; private set; }
341

    
342
        public ObjectInfo SetPrevious(ObjectInfo previous)
343
        {            
344
            Previous = previous;
345
            PreviousHash = previous.Hash;
346
            return this;
347
        }
348
    }
349
}