2 /* -----------------------------------------------------------------------
3 * <copyright file="ObjectInfo.cs" company="GRNet">
5 * Copyright 2011-2012 GRNET S.A. All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
11 * 1. Redistributions of source code must retain the above
12 * copyright notice, this list of conditions and the following
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.
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.
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.
39 * -----------------------------------------------------------------------
43 using System.Collections.Generic;
44 using System.Diagnostics;
45 using System.Diagnostics.Contracts;
47 using System.Globalization;
51 using Newtonsoft.Json;
53 namespace Pithos.Interfaces
55 [DebuggerDisplay("Name {Name}")]
56 public class ObjectInfo//:DynamicObject
58 private readonly List<string> _knownContainers= new List<string>{"trash"};
59 public string Name { get; set; }
62 public string Hash { get; set; }
64 public string X_Object_Hash { get { return Hash; } set { Hash = value; } }
66 [JsonProperty("x_object_uuid")]
67 public string UUID { get; set; }
69 public long Bytes { get; set; }
70 public string Content_Type { get; set; }
71 public DateTime Last_Modified { get; set; }
73 private Dictionary<string, string> _tags=new Dictionary<string, string>();
74 public Dictionary<string, string> Tags
77 set { _tags = value; }
80 private Dictionary<string, string> _extensions=new Dictionary<string, string>();
81 public Dictionary<string, string> Extensions
83 get { return _extensions; }
87 ExtractKnownExtensions();
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
97 get { return _permissions; }
100 _permissions = value;
107 [JsonProperty("x_object_version")]
108 public long? Version { get; set; }
112 /// Shared object permissions can be Read or Write
114 [JsonProperty("x_object_allowed_to")]
115 public string AllowedTo { get; set; }
119 /// Version timestamp
121 [JsonProperty("X_Object_Version_Timestamp"), JsonConverter(typeof(PithosDateTimeConverter))]
122 public DateTime? VersionTimestamp { get; set; }
124 [JsonProperty("X_Object_Modified_By")]
125 public string ModifiedBy { get; set; }
128 public Stream Stream { get; set; }
131 public Uri StorageUri { get; set; }
133 public string Account { get; set; }
135 public string Container { get; set; }
141 var relativeUrl=String.Format("{0}/{1}/{2}",Account, Container,Name);
142 return StorageUri==null
143 ? new Uri(relativeUrl,UriKind.Relative)
144 : new Uri(StorageUri, relativeUrl);
148 public string ContendDisposition { get; set; }
150 public string ContentEncoding { get; set; }
152 public string Manifest { get; set; }
156 get { return !String.IsNullOrWhiteSpace(PublicUrl); }
161 else if (String.IsNullOrWhiteSpace(PublicUrl))
166 [JsonProperty("X_Object_Public")]
167 public string PublicUrl { get; set; }
169 public string PreviousHash { get; set; }
174 public ObjectInfo(string accountPath,string accountName,FileSystemInfo fileInfo)
176 if (String.IsNullOrWhiteSpace(accountPath))
177 throw new ArgumentNullException("accountPath");
178 if (string.IsNullOrWhiteSpace(accountName))
179 throw new ArgumentNullException("accountName");
180 if (fileInfo == null)
181 throw new ArgumentNullException("fileInfo");
182 Contract.EndContractBlock();
184 var relativeUrl = fileInfo.WithProperCapitalization().AsRelativeUrlTo(accountPath);
185 //The first part of the URL is the container
186 var slashIndex = relativeUrl.IndexOf('/');
187 var container = relativeUrl.Substring(0, slashIndex);
188 //The second is the file's url relative to the container
189 var fileUrl = relativeUrl.Substring(slashIndex + 1);
191 Account = accountName;
192 Container = container;
197 private void ExtractKnownExtensions()
199 Version=GetLong(KnownExtensions.X_Object_Version);
200 VersionTimestamp = GetTimestamp(KnownExtensions.X_Object_Version_Timestamp);
201 ModifiedBy = GetString(KnownExtensions.X_Object_Modified_By);
204 private string GetString(string name)
207 _extensions.TryGetValue(name, out value);
211 private long? GetLong(string name)
215 return _extensions.TryGetValue(name, out version) && long.TryParse(version, out value)
220 private DateTime? GetTimestamp(string name)
224 if (_extensions.TryGetValue(name, out version) &&
225 DateTime.TryParse(version,CultureInfo.InvariantCulture,DateTimeStyles.AdjustToUniversal, out value))
233 public static ObjectInfo Empty = new ObjectInfo
238 Content_Type = String.Empty,
239 Last_Modified = DateTime.MinValue,
243 private bool _exists=true;
256 public string RelativeUrlToFilePath(string currentAccount)
259 throw new InvalidOperationException("Name can't be null");
260 if (String.IsNullOrWhiteSpace(currentAccount))
261 throw new ArgumentNullException("currentAccount");
262 Contract.EndContractBlock();
267 var unescaped = Uri.UnescapeDataString(Name);
268 var path = unescaped.Replace("/", "\\");
269 var pathParts=new Stack<string>();
270 pathParts.Push(path);
271 if (!String.IsNullOrWhiteSpace(Container) && !_knownContainers.Contains(Container))
272 pathParts.Push(Container);
273 if (!currentAccount.Equals(Account, StringComparison.InvariantCultureIgnoreCase))
277 pathParts.Push(Account);
278 pathParts.Push(FolderConstants.OthersFolder);
281 var finalPath=Path.Combine(pathParts.ToArray());
286 public override bool TrySetMember(SetMemberBinder binder, object value)
288 if (binder.Name.StartsWith("x_object_meta"))
290 Tags[binder.Name] = value.ToString();
296 public string GetPermissionString()
298 if (Permissions==null)
299 throw new InvalidOperationException();
300 Contract.EndContractBlock();
302 var permissionBuilder = new StringBuilder();
303 var groupings = Permissions.GroupBy(pair => pair.Value, pair => pair.Key);
304 foreach (var grouping in groupings)
306 permissionBuilder.AppendFormat("{0}={1};", grouping.Key, String.Join(",", grouping));
308 var permissions = permissionBuilder.ToString().Trim(';');
312 public void SetPermissions(string permissions)
314 if (String.IsNullOrWhiteSpace(permissions))
317 var permDict=new Dictionary<string, string>();
318 var perms=permissions.Split(';');
319 foreach (var perm in perms)
321 var permPairs=perm.Split('=');
322 var right = permPairs[0];
323 var users= permPairs[1].Split(new[]{','},StringSplitOptions.RemoveEmptyEntries);
324 foreach (var user in users)
326 permDict[user] = right;
329 Permissions = permDict;
332 //The previous values that correspond to a NoModification object
333 //have the same account, container and possibly the same folder
334 public bool CorrespondsTo(ObjectInfo other)
336 return other.Account == this.Account
337 && other.Container == this.Container
338 && (this.Name == null || other.Name.StartsWith(this.Name));
342 public ObjectInfo Previous { get; private set; }
344 public bool IsDirectory
348 if (Content_Type.StartsWith(@"application/directory",StringComparison.InvariantCultureIgnoreCase))
350 if (Content_Type.StartsWith(@"application/folder",StringComparison.InvariantCultureIgnoreCase))
356 public Uri AccountKey
358 get { return new Uri(StorageUri,"../" + Account); }
361 public ObjectInfo SetPrevious(ObjectInfo previous)
364 PreviousHash = previous.Hash;