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; }
61 public string ETag { get; set; }
63 public string Hash { get; set; }
65 public string X_Object_Hash { get { return Hash; } set { Hash = value; } }
67 [JsonProperty("x_object_uuid")]
68 public string UUID { get; set; }
70 public long Bytes { get; set; }
71 public string Content_Type { get; set; }
72 public DateTime Last_Modified { get; set; }
74 private Dictionary<string, string> _tags=new Dictionary<string, string>();
75 public Dictionary<string, string> Tags
78 set { _tags = value; }
81 private Dictionary<string, string> _extensions=new Dictionary<string, string>();
82 public Dictionary<string, string> Extensions
84 get { return _extensions; }
88 ExtractKnownExtensions();
93 private Dictionary<string, string> _permissions=new Dictionary<string, string>();
94 [JsonProperty("x_object_sharing")]
95 [JsonConverter(typeof(PermissionConverter))]
96 public Dictionary<string, string> Permissions
98 get { return _permissions; }
101 _permissions = value;
108 [JsonProperty("x_object_version")]
109 public long? Version { get; set; }
113 /// Shared object permissions can be Read or Write
115 [JsonProperty("x_object_allowed_to")]
116 public string AllowedTo { get; set; }
120 /// Version timestamp
122 [JsonProperty("X_Object_Version_Timestamp"), JsonConverter(typeof(PithosDateTimeConverter))]
123 public DateTime? VersionTimestamp { get; set; }
125 [JsonProperty("X_Object_Modified_By")]
126 public string ModifiedBy { get; set; }
129 public Stream Stream { get; set; }
132 public Uri StorageUri { get; set; }
134 public string Account { get; set; }
136 public string Container { get; set; }
142 var relativeUrl=String.Format("{0}/{1}/{2}",Account, Container,Name);
143 return StorageUri==null
144 ? new Uri(relativeUrl,UriKind.Relative)
145 : new Uri(StorageUri, relativeUrl);
149 public string ContendDisposition { get; set; }
151 public string ContentEncoding { get; set; }
153 public string Manifest { get; set; }
157 get { return !String.IsNullOrWhiteSpace(PublicUrl); }
162 else if (String.IsNullOrWhiteSpace(PublicUrl))
167 [JsonProperty("X_Object_Public")]
168 public string PublicUrl { get; set; }
170 public string PreviousHash { get; set; }
175 public ObjectInfo(string accountPath,string accountName,FileSystemInfo fileInfo)
177 if (String.IsNullOrWhiteSpace(accountPath))
178 throw new ArgumentNullException("accountPath");
179 if (string.IsNullOrWhiteSpace(accountName))
180 throw new ArgumentNullException("accountName");
181 if (fileInfo == null)
182 throw new ArgumentNullException("fileInfo");
183 Contract.EndContractBlock();
185 var relativeUrl = fileInfo.WithProperCapitalization().AsRelativeUrlTo(accountPath);
186 //The first part of the URL is the container
187 var slashIndex = relativeUrl.IndexOf('/');
188 var container = relativeUrl.Substring(0, slashIndex);
189 //The second is the file's url relative to the container
190 var fileUrl = relativeUrl.Substring(slashIndex + 1);
192 Account = accountName;
193 Container = container;
198 private void ExtractKnownExtensions()
200 Version=GetLong(KnownExtensions.X_Object_Version);
201 VersionTimestamp = GetTimestamp(KnownExtensions.X_Object_Version_Timestamp);
202 ModifiedBy = GetString(KnownExtensions.X_Object_Modified_By);
205 private string GetString(string name)
208 _extensions.TryGetValue(name, out value);
212 private long? GetLong(string name)
216 return _extensions.TryGetValue(name, out version) && long.TryParse(version, out value)
221 private DateTime? GetTimestamp(string name)
225 if (_extensions.TryGetValue(name, out version) &&
226 DateTime.TryParse(version,CultureInfo.InvariantCulture,DateTimeStyles.AdjustToUniversal, out value))
234 public static ObjectInfo Empty = new ObjectInfo
239 Content_Type = String.Empty,
240 Last_Modified = DateTime.MinValue,
244 private bool _exists=true;
257 public string RelativeUrlToFilePath(string currentAccount)
260 throw new InvalidOperationException("Name can't be null");
261 if (String.IsNullOrWhiteSpace(currentAccount))
262 throw new ArgumentNullException("currentAccount");
263 Contract.EndContractBlock();
268 var unescaped = Uri.UnescapeDataString(Name);
269 var path = unescaped.Replace("/", "\\");
270 var pathParts=new Stack<string>();
271 pathParts.Push(path);
272 if (!String.IsNullOrWhiteSpace(Container) && !_knownContainers.Contains(Container))
273 pathParts.Push(Container);
274 if (!currentAccount.Equals(Account, StringComparison.InvariantCultureIgnoreCase))
278 pathParts.Push(Account);
279 pathParts.Push(FolderConstants.OthersFolder);
282 var finalPath=Path.Combine(pathParts.ToArray());
287 public override bool TrySetMember(SetMemberBinder binder, object value)
289 if (binder.Name.StartsWith("x_object_meta"))
291 Tags[binder.Name] = value.ToString();
297 public string GetPermissionString()
299 if (Permissions==null)
300 throw new InvalidOperationException();
301 Contract.EndContractBlock();
303 if (Permissions.Count == 0)
305 var permissionBuilder = new StringBuilder();
306 var groupings = Permissions.GroupBy(pair => pair.Value.Trim(), pair => pair.Key.Trim());
307 foreach (var grouping in groupings)
309 permissionBuilder.AppendFormat("{0}={1};", grouping.Key, String.Join(",", grouping));
311 var permissions = Uri.EscapeDataString(permissionBuilder.ToString().Trim(';'));
315 public void SetPermissions(string permissions)
317 if (String.IsNullOrWhiteSpace(permissions))
320 Permissions = PermissionConverter.ParsePermissions(permissions);
323 //The previous values that correspond to a NoModification object
324 //have the same account, container and possibly the same folder
325 public bool CorrespondsTo(ObjectInfo other)
327 return other.Account == this.Account
328 && other.Container == this.Container
329 && (this.Name == null || other.Name.StartsWith(this.Name));
332 public bool IsWritable(string account)
334 //If the Allowed To header has no value, try to determine the Share permissions
335 if (AllowedTo == null)
337 //If this file has no permissions defined, we can probably write it
338 //This case should occur only when the info comes from a listing of the user's own files
339 if (Permissions == null || Permissions.Count == 0)
343 //Do we have an explicit write share to this account?
344 return Permissions.TryGetValue(account, out perms)
345 && perms.Equals("write",StringComparison.InvariantCultureIgnoreCase);
348 //Otherwise return the permissions specified by AllowedTo
349 return AllowedTo.Equals("write",StringComparison.InvariantCultureIgnoreCase) ;
352 public ObjectInfo Previous { get; private set; }
354 public bool IsDirectory
358 if (Content_Type == null)
360 if (Content_Type.StartsWith(@"application/directory",StringComparison.InvariantCultureIgnoreCase))
362 if (Content_Type.StartsWith(@"application/folder",StringComparison.InvariantCultureIgnoreCase))
368 public Uri AccountKey
370 get { return new Uri(StorageUri,"../" + Account); }
373 public ObjectInfo SetPrevious(ObjectInfo previous)
376 PreviousHash = previous.Hash;
380 public bool? IsShared
384 if (Uri == null || StorageUri == null)
386 var isShared = !Uri.ToString().StartsWith(StorageUri.ToString());