ServicePath.cs 22 KB

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