ServicePath.cs 22 KB

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