ServicePath.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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 string Path { get { return this.restPath; } }
  40. public string Summary { get; private set; }
  41. public string Description { get; private set; }
  42. public bool IsHidden { get; private set; }
  43. public int Priority { get; set; } //passed back to RouteAttribute
  44. public static string[] GetPathPartsForMatching(string pathInfo)
  45. {
  46. return pathInfo.ToLower().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, string path, string verbs, bool isHidden = false, string summary = null, string description = null)
  74. {
  75. this.RequestType = requestType;
  76. this.Summary = summary;
  77. this.IsHidden = isHidden;
  78. this.Description = description;
  79. this.restPath = path;
  80. this.Verbs = string.IsNullOrWhiteSpace(verbs) ? ServiceExecExtensions.AllVerbs : verbs.ToUpper().Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
  81. var componentsList = new List<string>();
  82. //We only split on '.' if the restPath has them. Allows for /{action}.{type}
  83. var hasSeparators = new List<bool>();
  84. foreach (var component in this.restPath.Split(PathSeperatorChar))
  85. {
  86. if (String.IsNullOrEmpty(component)) continue;
  87. if (StringContains(component, VariablePrefix)
  88. && component.IndexOf(ComponentSeperator) != -1)
  89. {
  90. hasSeparators.Add(true);
  91. componentsList.AddRange(component.Split(ComponentSeperator));
  92. }
  93. else
  94. {
  95. hasSeparators.Add(false);
  96. componentsList.Add(component);
  97. }
  98. }
  99. var components = componentsList.ToArray(componentsList.Count);
  100. this.TotalComponentsCount = components.Length;
  101. this.literalsToMatch = new string[this.TotalComponentsCount];
  102. this.variablesNames = new string[this.TotalComponentsCount];
  103. this.isWildcard = new bool[this.TotalComponentsCount];
  104. this.componentsWithSeparators = hasSeparators.ToArray(hasSeparators.Count);
  105. this.PathComponentsCount = this.componentsWithSeparators.Length;
  106. string firstLiteralMatch = null;
  107. for (var i = 0; i < components.Length; i++)
  108. {
  109. var component = components[i];
  110. if (component.StartsWith(VariablePrefix))
  111. {
  112. var variableName = component.Substring(1, component.Length - 2);
  113. if (variableName[variableName.Length - 1] == WildCardChar)
  114. {
  115. this.isWildcard[i] = true;
  116. variableName = variableName.Substring(0, variableName.Length - 1);
  117. }
  118. this.variablesNames[i] = variableName;
  119. this.VariableArgsCount++;
  120. }
  121. else
  122. {
  123. this.literalsToMatch[i] = component.ToLower();
  124. if (firstLiteralMatch == null)
  125. {
  126. firstLiteralMatch = this.literalsToMatch[i];
  127. }
  128. }
  129. }
  130. for (var i = 0; i < components.Length - 1; i++)
  131. {
  132. if (!this.isWildcard[i]) continue;
  133. if (this.literalsToMatch[i + 1] == null)
  134. {
  135. throw new ArgumentException(
  136. "A wildcard path component must be at the end of the path or followed by a literal path component.");
  137. }
  138. }
  139. this.wildcardCount = this.isWildcard.Count(x => x);
  140. this.IsWildCardPath = this.wildcardCount > 0;
  141. this.FirstMatchHashKey = !this.IsWildCardPath
  142. ? this.PathComponentsCount + PathSeperator + firstLiteralMatch
  143. : WildCardChar + PathSeperator + firstLiteralMatch;
  144. this.typeDeserializer = new StringMapTypeDeserializer(createInstanceFn, getParseFn, this.RequestType);
  145. RegisterCaseInsenstivePropertyNameMappings();
  146. }
  147. private void RegisterCaseInsenstivePropertyNameMappings()
  148. {
  149. foreach (var propertyInfo in GetSerializableProperties(RequestType))
  150. {
  151. var propertyName = propertyInfo.Name;
  152. propertyNamesMap.Add(propertyName.ToLower(), propertyName);
  153. }
  154. }
  155. internal static string[] IgnoreAttributesNamed = new[] {
  156. "IgnoreDataMemberAttribute",
  157. "JsonIgnoreAttribute"
  158. };
  159. private static Type excludeType = typeof(Stream);
  160. internal static List<PropertyInfo> GetSerializableProperties(Type type)
  161. {
  162. var list = new List<PropertyInfo>();
  163. var props = GetPublicProperties(type);
  164. foreach (var prop in props)
  165. {
  166. if (prop.GetMethod == null)
  167. {
  168. continue;
  169. }
  170. if (excludeType == prop.PropertyType)
  171. {
  172. continue;
  173. }
  174. var ignored = false;
  175. foreach (var attr in prop.GetCustomAttributes(true))
  176. {
  177. if (IgnoreAttributesNamed.Contains(attr.GetType().Name))
  178. {
  179. ignored = true;
  180. break;
  181. }
  182. }
  183. if (!ignored)
  184. {
  185. list.Add(prop);
  186. }
  187. }
  188. // else return those properties that are not decorated with IgnoreDataMember
  189. return list;
  190. }
  191. private static List<PropertyInfo> GetPublicProperties(Type type)
  192. {
  193. if (type.GetTypeInfo().IsInterface)
  194. {
  195. var propertyInfos = new List<PropertyInfo>();
  196. var considered = new List<Type>();
  197. var queue = new Queue<Type>();
  198. considered.Add(type);
  199. queue.Enqueue(type);
  200. while (queue.Count > 0)
  201. {
  202. var subType = queue.Dequeue();
  203. foreach (var subInterface in subType.GetTypeInfo().ImplementedInterfaces)
  204. {
  205. if (considered.Contains(subInterface)) continue;
  206. considered.Add(subInterface);
  207. queue.Enqueue(subInterface);
  208. }
  209. var typeProperties = GetTypesPublicProperties(subType);
  210. var newPropertyInfos = typeProperties
  211. .Where(x => !propertyInfos.Contains(x));
  212. propertyInfos.InsertRange(0, newPropertyInfos);
  213. }
  214. return propertyInfos;
  215. }
  216. var list = new List<PropertyInfo>();
  217. foreach (var t in GetTypesPublicProperties(type))
  218. {
  219. if (t.GetIndexParameters().Length == 0)
  220. {
  221. list.Add(t);
  222. }
  223. }
  224. return list;
  225. }
  226. private static PropertyInfo[] GetTypesPublicProperties(Type subType)
  227. {
  228. var pis = new List<PropertyInfo>();
  229. foreach (var pi in subType.GetRuntimeProperties())
  230. {
  231. var mi = pi.GetMethod ?? pi.SetMethod;
  232. if (mi != null && mi.IsStatic) continue;
  233. pis.Add(pi);
  234. }
  235. return pis.ToArray(pis.Count);
  236. }
  237. /// <summary>
  238. /// Provide for quick lookups based on hashes that can be determined from a request url
  239. /// </summary>
  240. public string FirstMatchHashKey { get; private set; }
  241. private readonly StringMapTypeDeserializer typeDeserializer;
  242. private readonly Dictionary<string, string> propertyNamesMap = new Dictionary<string, string>();
  243. public int MatchScore(string httpMethod, string[] withPathInfoParts, ILogger logger)
  244. {
  245. int wildcardMatchCount;
  246. var isMatch = IsMatch(httpMethod, withPathInfoParts, logger, out 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, ILogger logger, out int wildcardMatchCount)
  276. {
  277. wildcardMatchCount = 0;
  278. if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath)
  279. {
  280. //logger.Info("withPathInfoParts mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
  281. return false;
  282. }
  283. if (!Verbs.Contains(httpMethod, StringComparer.OrdinalIgnoreCase))
  284. {
  285. //logger.Info("allowsAllVerbs mismatch for {0} for {1} allowedverbs {2}", httpMethod, string.Join("/", withPathInfoParts), this.allowedVerbs);
  286. return false;
  287. }
  288. if (!ExplodeComponents(ref withPathInfoParts))
  289. {
  290. //logger.Info("ExplodeComponents mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
  291. return false;
  292. }
  293. if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath)
  294. {
  295. //logger.Info("TotalComponentsCount mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
  296. return false;
  297. }
  298. int pathIx = 0;
  299. for (var i = 0; i < this.TotalComponentsCount; i++)
  300. {
  301. if (this.isWildcard[i])
  302. {
  303. if (i < this.TotalComponentsCount - 1)
  304. {
  305. // Continue to consume up until a match with the next literal
  306. while (pathIx < withPathInfoParts.Length && !LiteralsEqual(withPathInfoParts[pathIx], this.literalsToMatch[i + 1]))
  307. {
  308. pathIx++;
  309. wildcardMatchCount++;
  310. }
  311. // Ensure there are still enough parts left to match the remainder
  312. if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1))
  313. {
  314. //logger.Info("withPathInfoParts length mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
  315. return false;
  316. }
  317. }
  318. else
  319. {
  320. // A wildcard at the end matches the remainder of path
  321. wildcardMatchCount += withPathInfoParts.Length - pathIx;
  322. pathIx = withPathInfoParts.Length;
  323. }
  324. }
  325. else
  326. {
  327. var literalToMatch = this.literalsToMatch[i];
  328. if (literalToMatch == null)
  329. {
  330. // Matching an ordinary (non-wildcard) variable consumes a single part
  331. pathIx++;
  332. continue;
  333. }
  334. if (withPathInfoParts.Length <= pathIx || !LiteralsEqual(withPathInfoParts[pathIx], literalToMatch))
  335. {
  336. //logger.Info("withPathInfoParts2 length mismatch for {0} for {1}. not equals: {2} != {3}.", httpMethod, string.Join("/", withPathInfoParts), withPathInfoParts[pathIx], literalToMatch);
  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(totalComponents.Count);
  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. }
  469. }