Statistics
| Branch: | Revision:

root / trunk / Pithos.Interfaces / ObjectInfo.cs @ b666b39a

History | View | Annotate | Download (11 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
        };
239

    
240
        
241

    
242
        public string RelativeUrlToFilePath(string currentAccount)
243
        {
244
            if (Name==null)
245
                throw new InvalidOperationException("Name can't be null");
246
            if (String.IsNullOrWhiteSpace(currentAccount))
247
                throw new ArgumentNullException("currentAccount");
248
            Contract.EndContractBlock();
249

    
250
            if (this == Empty)
251
                return String.Empty;
252

    
253
            var unescaped = Uri.UnescapeDataString(Name);
254
            var path = unescaped.Replace("/", "\\");
255
            var pathParts=new Stack<string>();
256
            pathParts.Push(path);
257
            if (!String.IsNullOrWhiteSpace(Container) && !_knownContainers.Contains(Container))
258
                pathParts.Push(Container);
259
            if (!currentAccount.Equals(Account, StringComparison.InvariantCultureIgnoreCase))
260
            {
261
                if (Account != null)
262
                {
263
                    pathParts.Push(Account);
264
                    pathParts.Push(FolderConstants.OthersFolder);
265
                }
266
            }
267
            var finalPath=Path.Combine(pathParts.ToArray());
268
            return finalPath;
269
        }
270

    
271
        public override bool TrySetMember(SetMemberBinder binder, object value)
272
        {
273
            if (binder.Name.StartsWith("x_object_meta"))
274
            {
275
                Tags[binder.Name] = value.ToString();
276
            }
277
            return false;
278
        }
279

    
280
        public string GetPermissionString()
281
        {
282
            if (Permissions==null)
283
                throw new InvalidOperationException();
284
            Contract.EndContractBlock();
285

    
286
            var permissionBuilder = new StringBuilder();
287
            var groupings = Permissions.GroupBy(pair => pair.Value, pair => pair.Key);
288
            foreach (var grouping in groupings)
289
            {
290
                permissionBuilder.AppendFormat("{0}={1};", grouping.Key, String.Join(",", grouping));
291
            }
292
            var permissions = permissionBuilder.ToString().Trim(';');
293
            return permissions;
294
        }
295

    
296
        public void SetPermissions(string permissions)
297
        {
298
            if (String.IsNullOrWhiteSpace(permissions))
299
                return;
300

    
301
            var permDict=new Dictionary<string, string>();
302
            var perms=permissions.Split(';');
303
            foreach (var perm in perms)
304
            {
305
                var permPairs=perm.Split('=');
306
                var right = permPairs[0];
307
                var users= permPairs[1].Split(new[]{','},StringSplitOptions.RemoveEmptyEntries);
308
                foreach (var user in users)
309
                {
310
                    permDict[user] = right;
311
                }
312
            }
313
            Permissions = permDict;
314
        }
315

    
316
        //The previous values that correspond to a NoModification object
317
        //have the same account, container and possibly the same folder
318
        public bool CorrespondsTo(ObjectInfo other)
319
        {
320
            return other.Account == this.Account
321
                   && other.Container == this.Container
322
                   && (this.Name == null || other.Name.StartsWith(this.Name));
323
        }
324

    
325

    
326
        public ObjectInfo Previous { get; private set; }
327

    
328
        public ObjectInfo SetPrevious(ObjectInfo previous)
329
        {            
330
            Previous = previous;
331
            PreviousHash = previous.Hash;
332
            return this;
333
        }
334
    }
335
}