RestPath.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using MediaBrowser.Model.Logging;
  7. using ServiceStack.Serialization;
  8. namespace ServiceStack.Host
  9. {
  10. public class RestPath
  11. {
  12. private const string WildCard = "*";
  13. private const char WildCardChar = '*';
  14. private const string PathSeperator = "/";
  15. private const char PathSeperatorChar = '/';
  16. private const char ComponentSeperator = '.';
  17. private const string VariablePrefix = "{";
  18. readonly bool[] componentsWithSeparators;
  19. private readonly string restPath;
  20. private readonly string allowedVerbs;
  21. private readonly bool allowsAllVerbs;
  22. public bool IsWildCardPath { get; private set; }
  23. private readonly string[] literalsToMatch;
  24. private readonly string[] variablesNames;
  25. private readonly bool[] isWildcard;
  26. private readonly int wildcardCount = 0;
  27. public int VariableArgsCount { get; set; }
  28. /// <summary>
  29. /// The number of segments separated by '/' determinable by path.Split('/').Length
  30. /// e.g. /path/to/here.ext == 3
  31. /// </summary>
  32. public int PathComponentsCount { get; set; }
  33. /// <summary>
  34. /// The total number of segments after subparts have been exploded ('.')
  35. /// e.g. /path/to/here.ext == 4
  36. /// </summary>
  37. public int TotalComponentsCount { get; set; }
  38. public string[] Verbs
  39. {
  40. get
  41. {
  42. return allowsAllVerbs
  43. ? new[] { ActionContext.AnyAction }
  44. : AllowedVerbs.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
  45. }
  46. }
  47. public Type RequestType { get; private set; }
  48. public string Path { get { return this.restPath; } }
  49. public string Summary { get; private set; }
  50. public string Notes { get; private set; }
  51. public bool AllowsAllVerbs { get { return this.allowsAllVerbs; } }
  52. public string AllowedVerbs { get { return this.allowedVerbs; } }
  53. public int Priority { get; set; } //passed back to RouteAttribute
  54. public static string[] GetPathPartsForMatching(string pathInfo)
  55. {
  56. var parts = pathInfo.ToLower().Split(PathSeperatorChar)
  57. .Where(x => !string.IsNullOrEmpty(x)).ToArray();
  58. return parts;
  59. }
  60. public static List<string> GetFirstMatchHashKeys(string[] pathPartsForMatching)
  61. {
  62. var hashPrefix = pathPartsForMatching.Length + PathSeperator;
  63. return GetPotentialMatchesWithPrefix(hashPrefix, pathPartsForMatching);
  64. }
  65. public static List<string> GetFirstMatchWildCardHashKeys(string[] pathPartsForMatching)
  66. {
  67. const string hashPrefix = WildCard + PathSeperator;
  68. return GetPotentialMatchesWithPrefix(hashPrefix, pathPartsForMatching);
  69. }
  70. private static List<string> GetPotentialMatchesWithPrefix(string hashPrefix, string[] pathPartsForMatching)
  71. {
  72. var list = new List<string>();
  73. foreach (var part in pathPartsForMatching)
  74. {
  75. list.Add(hashPrefix + part);
  76. var subParts = part.Split(ComponentSeperator);
  77. if (subParts.Length == 1) continue;
  78. foreach (var subPart in subParts)
  79. {
  80. list.Add(hashPrefix + subPart);
  81. }
  82. }
  83. return list;
  84. }
  85. public RestPath(Type requestType, string path, string verbs, string summary = null, string notes = null)
  86. {
  87. this.RequestType = requestType;
  88. this.Summary = summary;
  89. this.Notes = notes;
  90. this.restPath = path;
  91. this.allowsAllVerbs = verbs == null || string.Equals(verbs, WildCard, StringComparison.OrdinalIgnoreCase);
  92. if (!this.allowsAllVerbs)
  93. {
  94. this.allowedVerbs = verbs.ToUpper();
  95. }
  96. var componentsList = new List<string>();
  97. //We only split on '.' if the restPath has them. Allows for /{action}.{type}
  98. var hasSeparators = new List<bool>();
  99. foreach (var component in this.restPath.Split(PathSeperatorChar))
  100. {
  101. if (string.IsNullOrEmpty(component)) continue;
  102. if (StringContains(component, VariablePrefix)
  103. && component.IndexOf(ComponentSeperator) != -1)
  104. {
  105. hasSeparators.Add(true);
  106. componentsList.AddRange(component.Split(ComponentSeperator));
  107. }
  108. else
  109. {
  110. hasSeparators.Add(false);
  111. componentsList.Add(component);
  112. }
  113. }
  114. var components = componentsList.ToArray();
  115. this.TotalComponentsCount = components.Length;
  116. this.literalsToMatch = new string[this.TotalComponentsCount];
  117. this.variablesNames = new string[this.TotalComponentsCount];
  118. this.isWildcard = new bool[this.TotalComponentsCount];
  119. this.componentsWithSeparators = hasSeparators.ToArray();
  120. this.PathComponentsCount = this.componentsWithSeparators.Length;
  121. string firstLiteralMatch = null;
  122. var sbHashKey = new StringBuilder();
  123. for (var i = 0; i < components.Length; i++)
  124. {
  125. var component = components[i];
  126. if (component.StartsWith(VariablePrefix))
  127. {
  128. var variableName = component.Substring(1, component.Length - 2);
  129. if (variableName[variableName.Length - 1] == WildCardChar)
  130. {
  131. this.isWildcard[i] = true;
  132. variableName = variableName.Substring(0, variableName.Length - 1);
  133. }
  134. this.variablesNames[i] = variableName;
  135. this.VariableArgsCount++;
  136. }
  137. else
  138. {
  139. this.literalsToMatch[i] = component.ToLower();
  140. sbHashKey.Append(i + PathSeperatorChar.ToString() + this.literalsToMatch);
  141. if (firstLiteralMatch == null)
  142. {
  143. firstLiteralMatch = this.literalsToMatch[i];
  144. }
  145. }
  146. }
  147. for (var i = 0; i < components.Length - 1; i++)
  148. {
  149. if (!this.isWildcard[i]) continue;
  150. if (this.literalsToMatch[i + 1] == null)
  151. {
  152. throw new ArgumentException(
  153. "A wildcard path component must be at the end of the path or followed by a literal path component.");
  154. }
  155. }
  156. this.wildcardCount = this.isWildcard.Count(x => x);
  157. this.IsWildCardPath = this.wildcardCount > 0;
  158. this.FirstMatchHashKey = !this.IsWildCardPath
  159. ? this.PathComponentsCount + PathSeperator + firstLiteralMatch
  160. : WildCardChar + PathSeperator + firstLiteralMatch;
  161. this.IsValid = sbHashKey.Length > 0;
  162. this.UniqueMatchHashKey = sbHashKey.ToString();
  163. this.typeDeserializer = new StringMapTypeDeserializer(this.RequestType);
  164. RegisterCaseInsenstivePropertyNameMappings();
  165. }
  166. private void RegisterCaseInsenstivePropertyNameMappings()
  167. {
  168. foreach (var propertyInfo in RequestType.GetSerializableProperties())
  169. {
  170. var propertyName = propertyInfo.Name;
  171. propertyNamesMap.Add(propertyName.ToLower(), propertyName);
  172. }
  173. }
  174. public bool IsValid { get; set; }
  175. /// <summary>
  176. /// Provide for quick lookups based on hashes that can be determined from a request url
  177. /// </summary>
  178. public string FirstMatchHashKey { get; private set; }
  179. public string UniqueMatchHashKey { get; private set; }
  180. private readonly StringMapTypeDeserializer typeDeserializer;
  181. private readonly Dictionary<string, string> propertyNamesMap = new Dictionary<string, string>();
  182. public int MatchScore(string httpMethod, string[] withPathInfoParts, ILogger logger)
  183. {
  184. int wildcardMatchCount;
  185. var isMatch = IsMatch(httpMethod, withPathInfoParts, logger, out wildcardMatchCount);
  186. if (!isMatch)
  187. {
  188. return -1;
  189. }
  190. var score = 0;
  191. //Routes with least wildcard matches get the highest score
  192. score += Math.Max((100 - wildcardMatchCount), 1) * 1000;
  193. //Routes with less variable (and more literal) matches
  194. score += Math.Max((10 - VariableArgsCount), 1) * 100;
  195. //Exact verb match is better than ANY
  196. var exactVerb = string.Equals(httpMethod, AllowedVerbs, StringComparison.OrdinalIgnoreCase);
  197. score += exactVerb ? 10 : 1;
  198. return score;
  199. }
  200. private bool StringContains(string str1, string str2)
  201. {
  202. return str1.IndexOf(str2, StringComparison.OrdinalIgnoreCase) != -1;
  203. }
  204. /// <summary>
  205. /// For performance withPathInfoParts should already be a lower case string
  206. /// to minimize redundant matching operations.
  207. /// </summary>
  208. public bool IsMatch(string httpMethod, string[] withPathInfoParts, ILogger logger, out int wildcardMatchCount)
  209. {
  210. wildcardMatchCount = 0;
  211. if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath)
  212. {
  213. //logger.Info("withPathInfoParts mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
  214. return false;
  215. }
  216. if (!this.allowsAllVerbs && !StringContains(this.allowedVerbs, httpMethod))
  217. {
  218. //logger.Info("allowsAllVerbs mismatch for {0} for {1} allowedverbs {2}", httpMethod, string.Join("/", withPathInfoParts), this.allowedVerbs);
  219. return false;
  220. }
  221. if (!ExplodeComponents(ref withPathInfoParts))
  222. {
  223. //logger.Info("ExplodeComponents mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
  224. return false;
  225. }
  226. if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath)
  227. {
  228. //logger.Info("TotalComponentsCount mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
  229. return false;
  230. }
  231. int pathIx = 0;
  232. for (var i = 0; i < this.TotalComponentsCount; i++)
  233. {
  234. if (this.isWildcard[i])
  235. {
  236. if (i < this.TotalComponentsCount - 1)
  237. {
  238. // Continue to consume up until a match with the next literal
  239. while (pathIx < withPathInfoParts.Length && !LiteralsEqual(withPathInfoParts[pathIx], this.literalsToMatch[i + 1]))
  240. {
  241. pathIx++;
  242. wildcardMatchCount++;
  243. }
  244. // Ensure there are still enough parts left to match the remainder
  245. if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1))
  246. {
  247. //logger.Info("withPathInfoParts length mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
  248. return false;
  249. }
  250. }
  251. else
  252. {
  253. // A wildcard at the end matches the remainder of path
  254. wildcardMatchCount += withPathInfoParts.Length - pathIx;
  255. pathIx = withPathInfoParts.Length;
  256. }
  257. }
  258. else
  259. {
  260. var literalToMatch = this.literalsToMatch[i];
  261. if (literalToMatch == null)
  262. {
  263. // Matching an ordinary (non-wildcard) variable consumes a single part
  264. pathIx++;
  265. continue;
  266. }
  267. if (withPathInfoParts.Length <= pathIx || !LiteralsEqual(withPathInfoParts[pathIx], literalToMatch))
  268. {
  269. //logger.Info("withPathInfoParts2 length mismatch for {0} for {1}. not equals: {2} != {3}.", httpMethod, string.Join("/", withPathInfoParts), withPathInfoParts[pathIx], literalToMatch);
  270. return false;
  271. }
  272. pathIx++;
  273. }
  274. }
  275. return pathIx == withPathInfoParts.Length;
  276. }
  277. private bool LiteralsEqual(string str1, string str2)
  278. {
  279. // Most cases
  280. if (string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))
  281. {
  282. return true;
  283. }
  284. // Handle turkish i
  285. str1 = str1.ToUpperInvariant();
  286. str2 = str2.ToUpperInvariant();
  287. // Invariant IgnoreCase would probably be better but it's not available in PCL
  288. return string.Equals(str1, str2, StringComparison.CurrentCultureIgnoreCase);
  289. }
  290. private bool ExplodeComponents(ref string[] withPathInfoParts)
  291. {
  292. var totalComponents = new List<string>();
  293. for (var i = 0; i < withPathInfoParts.Length; i++)
  294. {
  295. var component = withPathInfoParts[i];
  296. if (string.IsNullOrEmpty(component)) continue;
  297. if (this.PathComponentsCount != this.TotalComponentsCount
  298. && this.componentsWithSeparators[i])
  299. {
  300. var subComponents = component.Split(ComponentSeperator);
  301. if (subComponents.Length < 2) return false;
  302. totalComponents.AddRange(subComponents);
  303. }
  304. else
  305. {
  306. totalComponents.Add(component);
  307. }
  308. }
  309. withPathInfoParts = totalComponents.ToArray();
  310. return true;
  311. }
  312. public object CreateRequest(string pathInfo, Dictionary<string, string> queryStringAndFormData, object fromInstance)
  313. {
  314. var requestComponents = pathInfo.Split(PathSeperatorChar)
  315. .Where(x => !string.IsNullOrEmpty(x)).ToArray();
  316. ExplodeComponents(ref requestComponents);
  317. if (requestComponents.Length != this.TotalComponentsCount)
  318. {
  319. var isValidWildCardPath = this.IsWildCardPath
  320. && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount;
  321. if (!isValidWildCardPath)
  322. throw new ArgumentException(string.Format(
  323. "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'",
  324. pathInfo, this.restPath));
  325. }
  326. var requestKeyValuesMap = new Dictionary<string, string>();
  327. var pathIx = 0;
  328. for (var i = 0; i < this.TotalComponentsCount; i++)
  329. {
  330. var variableName = this.variablesNames[i];
  331. if (variableName == null)
  332. {
  333. pathIx++;
  334. continue;
  335. }
  336. string propertyNameOnRequest;
  337. if (!this.propertyNamesMap.TryGetValue(variableName.ToLower(), out propertyNameOnRequest))
  338. {
  339. if (string.Equals("ignore", variableName, StringComparison.OrdinalIgnoreCase))
  340. {
  341. pathIx++;
  342. continue;
  343. }
  344. throw new ArgumentException("Could not find property "
  345. + variableName + " on " + RequestType.GetOperationName());
  346. }
  347. var value = requestComponents.Length > pathIx ? requestComponents[pathIx] : null; //wildcard has arg mismatch
  348. if (value != null && this.isWildcard[i])
  349. {
  350. if (i == this.TotalComponentsCount - 1)
  351. {
  352. // Wildcard at end of path definition consumes all the rest
  353. var sb = new StringBuilder();
  354. sb.Append(value);
  355. for (var j = pathIx + 1; j < requestComponents.Length; j++)
  356. {
  357. sb.Append(PathSeperatorChar + requestComponents[j]);
  358. }
  359. value = sb.ToString();
  360. }
  361. else
  362. {
  363. // Wildcard in middle of path definition consumes up until it
  364. // hits a match for the next element in the definition (which must be a literal)
  365. // It may consume 0 or more path parts
  366. var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1];
  367. if (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  368. {
  369. var sb = new StringBuilder();
  370. sb.Append(value);
  371. pathIx++;
  372. while (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  373. {
  374. sb.Append(PathSeperatorChar + requestComponents[pathIx++]);
  375. }
  376. value = sb.ToString();
  377. }
  378. else
  379. {
  380. value = null;
  381. }
  382. }
  383. }
  384. else
  385. {
  386. // Variable consumes single path item
  387. pathIx++;
  388. }
  389. requestKeyValuesMap[propertyNameOnRequest] = value;
  390. }
  391. if (queryStringAndFormData != null)
  392. {
  393. //Query String and form data can override variable path matches
  394. //path variables < query string < form data
  395. foreach (var name in queryStringAndFormData)
  396. {
  397. requestKeyValuesMap[name.Key] = name.Value;
  398. }
  399. }
  400. return this.typeDeserializer.PopulateFromMap(fromInstance, requestKeyValuesMap);
  401. }
  402. public override int GetHashCode()
  403. {
  404. return UniqueMatchHashKey.GetHashCode();
  405. }
  406. }
  407. }