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