ServicePath.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. namespace Emby.Server.Implementations.Services
  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[] { "ANY" }
  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(Func<Type, object> createInstanceFn, Func<Type, Func<string, object>> getParseFn, 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(createInstanceFn, getParseFn, this.RequestType);
  164. RegisterCaseInsenstivePropertyNameMappings();
  165. }
  166. private void RegisterCaseInsenstivePropertyNameMappings()
  167. {
  168. foreach (var propertyInfo in GetSerializableProperties(RequestType))
  169. {
  170. var propertyName = propertyInfo.Name;
  171. propertyNamesMap.Add(propertyName.ToLower(), propertyName);
  172. }
  173. }
  174. internal static string[] IgnoreAttributesNamed = new[] {
  175. "IgnoreDataMemberAttribute",
  176. "JsonIgnoreAttribute"
  177. };
  178. private static List<Type> _excludeTypes = new List<Type> { typeof(Stream) };
  179. internal static PropertyInfo[] GetSerializableProperties(Type type)
  180. {
  181. var properties = GetPublicProperties(type);
  182. var readableProperties = properties.Where(x => x.GetMethod != null);
  183. // else return those properties that are not decorated with IgnoreDataMember
  184. return readableProperties
  185. .Where(prop => prop.GetCustomAttributes(true)
  186. .All(attr =>
  187. {
  188. var name = attr.GetType().Name;
  189. return !IgnoreAttributesNamed.Contains(name);
  190. }))
  191. .Where(prop => !_excludeTypes.Contains(prop.PropertyType))
  192. .ToArray();
  193. }
  194. private static 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.ToArray();
  218. }
  219. return GetTypesPublicProperties(type)
  220. .Where(t => t.GetIndexParameters().Length == 0) // ignore indexed properties
  221. .ToArray();
  222. }
  223. private static PropertyInfo[] GetTypesPublicProperties(Type subType)
  224. {
  225. var pis = new List<PropertyInfo>();
  226. foreach (var pi in subType.GetRuntimeProperties())
  227. {
  228. var mi = pi.GetMethod ?? pi.SetMethod;
  229. if (mi != null && mi.IsStatic) continue;
  230. pis.Add(pi);
  231. }
  232. return pis.ToArray();
  233. }
  234. public bool IsValid { get; set; }
  235. /// <summary>
  236. /// Provide for quick lookups based on hashes that can be determined from a request url
  237. /// </summary>
  238. public string FirstMatchHashKey { get; private set; }
  239. public string UniqueMatchHashKey { get; private set; }
  240. private readonly StringMapTypeDeserializer typeDeserializer;
  241. private readonly Dictionary<string, string> propertyNamesMap = new Dictionary<string, string>();
  242. public int MatchScore(string httpMethod, string[] withPathInfoParts, ILogger logger)
  243. {
  244. int wildcardMatchCount;
  245. var isMatch = IsMatch(httpMethod, withPathInfoParts, logger, out wildcardMatchCount);
  246. if (!isMatch)
  247. {
  248. return -1;
  249. }
  250. var score = 0;
  251. //Routes with least wildcard matches get the highest score
  252. score += Math.Max((100 - wildcardMatchCount), 1) * 1000;
  253. //Routes with less variable (and more literal) matches
  254. score += Math.Max((10 - VariableArgsCount), 1) * 100;
  255. //Exact verb match is better than ANY
  256. var exactVerb = String.Equals(httpMethod, AllowedVerbs, StringComparison.OrdinalIgnoreCase);
  257. score += exactVerb ? 10 : 1;
  258. return score;
  259. }
  260. private bool StringContains(string str1, string str2)
  261. {
  262. return str1.IndexOf(str2, StringComparison.OrdinalIgnoreCase) != -1;
  263. }
  264. /// <summary>
  265. /// For performance withPathInfoParts should already be a lower case string
  266. /// to minimize redundant matching operations.
  267. /// </summary>
  268. public bool IsMatch(string httpMethod, string[] withPathInfoParts, ILogger logger, out int wildcardMatchCount)
  269. {
  270. wildcardMatchCount = 0;
  271. if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath)
  272. {
  273. //logger.Info("withPathInfoParts mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
  274. return false;
  275. }
  276. if (!this.allowsAllVerbs && !StringContains(this.allowedVerbs, httpMethod))
  277. {
  278. //logger.Info("allowsAllVerbs mismatch for {0} for {1} allowedverbs {2}", httpMethod, string.Join("/", withPathInfoParts), this.allowedVerbs);
  279. return false;
  280. }
  281. if (!ExplodeComponents(ref withPathInfoParts))
  282. {
  283. //logger.Info("ExplodeComponents mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
  284. return false;
  285. }
  286. if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath)
  287. {
  288. //logger.Info("TotalComponentsCount mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
  289. return false;
  290. }
  291. int pathIx = 0;
  292. for (var i = 0; i < this.TotalComponentsCount; i++)
  293. {
  294. if (this.isWildcard[i])
  295. {
  296. if (i < this.TotalComponentsCount - 1)
  297. {
  298. // Continue to consume up until a match with the next literal
  299. while (pathIx < withPathInfoParts.Length && !LiteralsEqual(withPathInfoParts[pathIx], this.literalsToMatch[i + 1]))
  300. {
  301. pathIx++;
  302. wildcardMatchCount++;
  303. }
  304. // Ensure there are still enough parts left to match the remainder
  305. if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1))
  306. {
  307. //logger.Info("withPathInfoParts length mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
  308. return false;
  309. }
  310. }
  311. else
  312. {
  313. // A wildcard at the end matches the remainder of path
  314. wildcardMatchCount += withPathInfoParts.Length - pathIx;
  315. pathIx = withPathInfoParts.Length;
  316. }
  317. }
  318. else
  319. {
  320. var literalToMatch = this.literalsToMatch[i];
  321. if (literalToMatch == null)
  322. {
  323. // Matching an ordinary (non-wildcard) variable consumes a single part
  324. pathIx++;
  325. continue;
  326. }
  327. if (withPathInfoParts.Length <= pathIx || !LiteralsEqual(withPathInfoParts[pathIx], literalToMatch))
  328. {
  329. //logger.Info("withPathInfoParts2 length mismatch for {0} for {1}. not equals: {2} != {3}.", httpMethod, string.Join("/", withPathInfoParts), withPathInfoParts[pathIx], literalToMatch);
  330. return false;
  331. }
  332. pathIx++;
  333. }
  334. }
  335. return pathIx == withPathInfoParts.Length;
  336. }
  337. private bool LiteralsEqual(string str1, string str2)
  338. {
  339. // Most cases
  340. if (String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))
  341. {
  342. return true;
  343. }
  344. // Handle turkish i
  345. str1 = str1.ToUpperInvariant();
  346. str2 = str2.ToUpperInvariant();
  347. // Invariant IgnoreCase would probably be better but it's not available in PCL
  348. return String.Equals(str1, str2, StringComparison.CurrentCultureIgnoreCase);
  349. }
  350. private bool ExplodeComponents(ref string[] withPathInfoParts)
  351. {
  352. var totalComponents = new List<string>();
  353. for (var i = 0; i < withPathInfoParts.Length; i++)
  354. {
  355. var component = withPathInfoParts[i];
  356. if (String.IsNullOrEmpty(component)) continue;
  357. if (this.PathComponentsCount != this.TotalComponentsCount
  358. && this.componentsWithSeparators[i])
  359. {
  360. var subComponents = component.Split(ComponentSeperator);
  361. if (subComponents.Length < 2) return false;
  362. totalComponents.AddRange(subComponents);
  363. }
  364. else
  365. {
  366. totalComponents.Add(component);
  367. }
  368. }
  369. withPathInfoParts = totalComponents.ToArray();
  370. return true;
  371. }
  372. public object CreateRequest(string pathInfo, Dictionary<string, string> queryStringAndFormData, object fromInstance)
  373. {
  374. var requestComponents = pathInfo.Split(PathSeperatorChar)
  375. .Where(x => !String.IsNullOrEmpty(x)).ToArray();
  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. string propertyNameOnRequest;
  397. if (!this.propertyNamesMap.TryGetValue(variableName.ToLower(), out propertyNameOnRequest))
  398. {
  399. if (String.Equals("ignore", variableName, StringComparison.OrdinalIgnoreCase))
  400. {
  401. pathIx++;
  402. continue;
  403. }
  404. throw new ArgumentException("Could not find property "
  405. + variableName + " on " + RequestType.GetMethodName());
  406. }
  407. var value = requestComponents.Length > pathIx ? requestComponents[pathIx] : null; //wildcard has arg mismatch
  408. if (value != null && this.isWildcard[i])
  409. {
  410. if (i == this.TotalComponentsCount - 1)
  411. {
  412. // Wildcard at end of path definition consumes all the rest
  413. var sb = new StringBuilder();
  414. sb.Append(value);
  415. for (var j = pathIx + 1; j < requestComponents.Length; j++)
  416. {
  417. sb.Append(PathSeperatorChar + requestComponents[j]);
  418. }
  419. value = sb.ToString();
  420. }
  421. else
  422. {
  423. // Wildcard in middle of path definition consumes up until it
  424. // hits a match for the next element in the definition (which must be a literal)
  425. // It may consume 0 or more path parts
  426. var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1];
  427. if (!String.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  428. {
  429. var sb = new StringBuilder();
  430. sb.Append(value);
  431. pathIx++;
  432. while (!String.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  433. {
  434. sb.Append(PathSeperatorChar + requestComponents[pathIx++]);
  435. }
  436. value = sb.ToString();
  437. }
  438. else
  439. {
  440. value = null;
  441. }
  442. }
  443. }
  444. else
  445. {
  446. // Variable consumes single path item
  447. pathIx++;
  448. }
  449. requestKeyValuesMap[propertyNameOnRequest] = value;
  450. }
  451. if (queryStringAndFormData != null)
  452. {
  453. //Query String and form data can override variable path matches
  454. //path variables < query string < form data
  455. foreach (var name in queryStringAndFormData)
  456. {
  457. requestKeyValuesMap[name.Key] = name.Value;
  458. }
  459. }
  460. return this.typeDeserializer.PopulateFromMap(fromInstance, requestKeyValuesMap);
  461. }
  462. public override int GetHashCode()
  463. {
  464. return UniqueMatchHashKey.GetHashCode();
  465. }
  466. }
  467. }