2
0

ServicePath.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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 { 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)
  250. {
  251. int wildcardMatchCount;
  252. var isMatch = IsMatch(httpMethod, withPathInfoParts, 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, out int wildcardMatchCount)
  282. {
  283. wildcardMatchCount = 0;
  284. if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath)
  285. {
  286. return false;
  287. }
  288. if (!Verbs.Contains(httpMethod, StringComparer.OrdinalIgnoreCase))
  289. {
  290. return false;
  291. }
  292. if (!ExplodeComponents(ref withPathInfoParts))
  293. {
  294. return false;
  295. }
  296. if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath)
  297. {
  298. return false;
  299. }
  300. int pathIx = 0;
  301. for (var i = 0; i < this.TotalComponentsCount; i++)
  302. {
  303. if (this.isWildcard[i])
  304. {
  305. if (i < this.TotalComponentsCount - 1)
  306. {
  307. // Continue to consume up until a match with the next literal
  308. while (pathIx < withPathInfoParts.Length && !LiteralsEqual(withPathInfoParts[pathIx], this.literalsToMatch[i + 1]))
  309. {
  310. pathIx++;
  311. wildcardMatchCount++;
  312. }
  313. // Ensure there are still enough parts left to match the remainder
  314. if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1))
  315. {
  316. return false;
  317. }
  318. }
  319. else
  320. {
  321. // A wildcard at the end matches the remainder of path
  322. wildcardMatchCount += withPathInfoParts.Length - pathIx;
  323. pathIx = withPathInfoParts.Length;
  324. }
  325. }
  326. else
  327. {
  328. var literalToMatch = this.literalsToMatch[i];
  329. if (literalToMatch == null)
  330. {
  331. // Matching an ordinary (non-wildcard) variable consumes a single part
  332. pathIx++;
  333. continue;
  334. }
  335. if (withPathInfoParts.Length <= pathIx || !LiteralsEqual(withPathInfoParts[pathIx], literalToMatch))
  336. {
  337. return false;
  338. }
  339. pathIx++;
  340. }
  341. }
  342. return pathIx == withPathInfoParts.Length;
  343. }
  344. private bool LiteralsEqual(string str1, string str2)
  345. {
  346. // Most cases
  347. if (String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))
  348. {
  349. return true;
  350. }
  351. // Handle turkish i
  352. str1 = str1.ToUpperInvariant();
  353. str2 = str2.ToUpperInvariant();
  354. // Invariant IgnoreCase would probably be better but it's not available in PCL
  355. return String.Equals(str1, str2, StringComparison.CurrentCultureIgnoreCase);
  356. }
  357. private bool ExplodeComponents(ref string[] withPathInfoParts)
  358. {
  359. var totalComponents = new List<string>();
  360. for (var i = 0; i < withPathInfoParts.Length; i++)
  361. {
  362. var component = withPathInfoParts[i];
  363. if (String.IsNullOrEmpty(component)) continue;
  364. if (this.PathComponentsCount != this.TotalComponentsCount
  365. && this.componentsWithSeparators[i])
  366. {
  367. var subComponents = component.Split(ComponentSeperator);
  368. if (subComponents.Length < 2) return false;
  369. totalComponents.AddRange(subComponents);
  370. }
  371. else
  372. {
  373. totalComponents.Add(component);
  374. }
  375. }
  376. withPathInfoParts = totalComponents.ToArray();
  377. return true;
  378. }
  379. public object CreateRequest(string pathInfo, Dictionary<string, string> queryStringAndFormData, object fromInstance)
  380. {
  381. var requestComponents = pathInfo.Split(new[] { PathSeperatorChar }, StringSplitOptions.RemoveEmptyEntries);
  382. ExplodeComponents(ref requestComponents);
  383. if (requestComponents.Length != this.TotalComponentsCount)
  384. {
  385. var isValidWildCardPath = this.IsWildCardPath
  386. && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount;
  387. if (!isValidWildCardPath)
  388. throw new ArgumentException(String.Format(
  389. "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'",
  390. pathInfo, this.restPath));
  391. }
  392. var requestKeyValuesMap = new Dictionary<string, string>();
  393. var pathIx = 0;
  394. for (var i = 0; i < this.TotalComponentsCount; i++)
  395. {
  396. var variableName = this.variablesNames[i];
  397. if (variableName == null)
  398. {
  399. pathIx++;
  400. continue;
  401. }
  402. string propertyNameOnRequest;
  403. if (!this.propertyNamesMap.TryGetValue(variableName.ToLower(), out propertyNameOnRequest))
  404. {
  405. if (String.Equals("ignore", variableName, StringComparison.OrdinalIgnoreCase))
  406. {
  407. pathIx++;
  408. continue;
  409. }
  410. throw new ArgumentException("Could not find property "
  411. + variableName + " on " + RequestType.GetMethodName());
  412. }
  413. var value = requestComponents.Length > pathIx ? requestComponents[pathIx] : null; //wildcard has arg mismatch
  414. if (value != null && this.isWildcard[i])
  415. {
  416. if (i == this.TotalComponentsCount - 1)
  417. {
  418. // Wildcard at end of path definition consumes all the rest
  419. var sb = new StringBuilder();
  420. sb.Append(value);
  421. for (var j = pathIx + 1; j < requestComponents.Length; j++)
  422. {
  423. sb.Append(PathSeperatorChar + requestComponents[j]);
  424. }
  425. value = sb.ToString();
  426. }
  427. else
  428. {
  429. // Wildcard in middle of path definition consumes up until it
  430. // hits a match for the next element in the definition (which must be a literal)
  431. // It may consume 0 or more path parts
  432. var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1];
  433. if (!String.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  434. {
  435. var sb = new StringBuilder();
  436. sb.Append(value);
  437. pathIx++;
  438. while (!String.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  439. {
  440. sb.Append(PathSeperatorChar + requestComponents[pathIx++]);
  441. }
  442. value = sb.ToString();
  443. }
  444. else
  445. {
  446. value = null;
  447. }
  448. }
  449. }
  450. else
  451. {
  452. // Variable consumes single path item
  453. pathIx++;
  454. }
  455. requestKeyValuesMap[propertyNameOnRequest] = value;
  456. }
  457. if (queryStringAndFormData != null)
  458. {
  459. //Query String and form data can override variable path matches
  460. //path variables < query string < form data
  461. foreach (var name in queryStringAndFormData)
  462. {
  463. requestKeyValuesMap[name.Key] = name.Value;
  464. }
  465. }
  466. return this.typeDeserializer.PopulateFromMap(fromInstance, requestKeyValuesMap);
  467. }
  468. public class RestPathMap : SortedDictionary<string, List<RestPath>>
  469. {
  470. public RestPathMap() : base(StringComparer.OrdinalIgnoreCase)
  471. {
  472. }
  473. }
  474. }
  475. }