ServicePath.cs 21 KB

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