ItemController.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Controller.Events;
  8. using MediaBrowser.Controller.IO;
  9. using MediaBrowser.Controller.Resolvers;
  10. using MediaBrowser.Model.Entities;
  11. namespace MediaBrowser.Controller.Library
  12. {
  13. public class ItemController
  14. {
  15. #region PreBeginResolvePath Event
  16. /// <summary>
  17. /// Fires when a path is about to be resolved, but before child folders and files
  18. /// have been collected from the file system.
  19. /// This gives listeners a chance to cancel the operation and cause the path to be ignored.
  20. /// </summary>
  21. public event EventHandler<PreBeginResolveEventArgs> PreBeginResolvePath;
  22. private bool OnPreBeginResolvePath(Folder parent, string path, FileAttributes attributes)
  23. {
  24. PreBeginResolveEventArgs args = new PreBeginResolveEventArgs()
  25. {
  26. Path = path,
  27. Parent = parent,
  28. FileAttributes = attributes,
  29. Cancel = false
  30. };
  31. if (PreBeginResolvePath != null)
  32. {
  33. PreBeginResolvePath(this, args);
  34. }
  35. return !args.Cancel;
  36. }
  37. #endregion
  38. #region BeginResolvePath Event
  39. /// <summary>
  40. /// Fires when a path is about to be resolved, but after child folders and files
  41. /// have been collected from the file system.
  42. /// This gives listeners a chance to cancel the operation and cause the path to be ignored.
  43. /// </summary>
  44. public event EventHandler<ItemResolveEventArgs> BeginResolvePath;
  45. private bool OnBeginResolvePath(ItemResolveEventArgs args)
  46. {
  47. if (BeginResolvePath != null)
  48. {
  49. BeginResolvePath(this, args);
  50. }
  51. return !args.Cancel;
  52. }
  53. #endregion
  54. private async Task<BaseItem> ResolveItem(ItemResolveEventArgs args)
  55. {
  56. // Try first priority resolvers
  57. foreach (IBaseItemResolver resolver in Kernel.Instance.EntityResolvers.Where(p => p.Priority == ResolverPriority.First))
  58. {
  59. var item = await resolver.ResolvePath(args);
  60. if (item != null)
  61. {
  62. return item;
  63. }
  64. }
  65. // Try second priority resolvers
  66. foreach (IBaseItemResolver resolver in Kernel.Instance.EntityResolvers.Where(p => p.Priority == ResolverPriority.Second))
  67. {
  68. var item = await resolver.ResolvePath(args);
  69. if (item != null)
  70. {
  71. return item;
  72. }
  73. }
  74. // Try third priority resolvers
  75. foreach (IBaseItemResolver resolver in Kernel.Instance.EntityResolvers.Where(p => p.Priority == ResolverPriority.Third))
  76. {
  77. var item = await resolver.ResolvePath(args);
  78. if (item != null)
  79. {
  80. return item;
  81. }
  82. }
  83. // Try last priority resolvers
  84. foreach (IBaseItemResolver resolver in Kernel.Instance.EntityResolvers.Where(p => p.Priority == ResolverPriority.Last))
  85. {
  86. var item = await resolver.ResolvePath(args);
  87. if (item != null)
  88. {
  89. return item;
  90. }
  91. }
  92. return null;
  93. }
  94. /// <summary>
  95. /// Resolves a path into a BaseItem
  96. /// </summary>
  97. public async Task<BaseItem> GetItem(Folder parent, string path)
  98. {
  99. return await GetItemInternal(parent, path, File.GetAttributes(path));
  100. }
  101. /// <summary>
  102. /// Resolves a path into a BaseItem
  103. /// </summary>
  104. private async Task<BaseItem> GetItemInternal(Folder parent, string path, FileAttributes attributes)
  105. {
  106. if (!OnPreBeginResolvePath(parent, path, attributes))
  107. {
  108. return null;
  109. }
  110. IEnumerable<KeyValuePair<string, FileAttributes>> fileSystemChildren;
  111. // Gather child folder and files
  112. if (attributes.HasFlag(FileAttributes.Directory))
  113. {
  114. fileSystemChildren = Directory.GetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly).Select(f => new KeyValuePair<string, FileAttributes>(f, File.GetAttributes(f)));
  115. bool isVirtualFolder = parent != null && parent.IsRoot;
  116. fileSystemChildren = FilterChildFileSystemEntries(fileSystemChildren, isVirtualFolder);
  117. }
  118. else
  119. {
  120. fileSystemChildren = new KeyValuePair<string, FileAttributes>[] { };
  121. }
  122. ItemResolveEventArgs args = new ItemResolveEventArgs()
  123. {
  124. Path = path,
  125. FileAttributes = attributes,
  126. FileSystemChildren = fileSystemChildren,
  127. Parent = parent,
  128. Cancel = false
  129. };
  130. // Fire BeginResolvePath to see if anyone wants to cancel this operation
  131. if (!OnBeginResolvePath(args))
  132. {
  133. return null;
  134. }
  135. BaseItem item = await ResolveItem(args);
  136. var folder = item as Folder;
  137. if (folder != null)
  138. {
  139. // If it's a folder look for child entities
  140. await AttachChildren(folder, fileSystemChildren);
  141. }
  142. return item;
  143. }
  144. /// <summary>
  145. /// Finds child BaseItems for a given Folder
  146. /// </summary>
  147. private async Task AttachChildren(Folder folder, IEnumerable<KeyValuePair<string, FileAttributes>> fileSystemChildren)
  148. {
  149. KeyValuePair<string, FileAttributes>[] fileSystemChildrenArray = fileSystemChildren.ToArray();
  150. int count = fileSystemChildrenArray.Length;
  151. Task<BaseItem>[] tasks = new Task<BaseItem>[count];
  152. for (int i = 0; i < count; i++)
  153. {
  154. var child = fileSystemChildrenArray[i];
  155. tasks[i] = GetItemInternal(folder, child.Key, child.Value);
  156. }
  157. BaseItem[] baseItemChildren = await Task<BaseItem>.WhenAll(tasks);
  158. // Sort them
  159. folder.Children = baseItemChildren.Where(i => i != null).OrderBy(f =>
  160. {
  161. return string.IsNullOrEmpty(f.SortName) ? f.Name : f.SortName;
  162. }).ToArray();
  163. }
  164. /// <summary>
  165. /// Transforms shortcuts into their actual paths
  166. /// </summary>
  167. private List<KeyValuePair<string, FileAttributes>> FilterChildFileSystemEntries(IEnumerable<KeyValuePair<string, FileAttributes>> fileSystemChildren, bool flattenShortcuts)
  168. {
  169. List<KeyValuePair<string, FileAttributes>> returnFiles = new List<KeyValuePair<string, FileAttributes>>();
  170. // Loop through each file
  171. foreach (KeyValuePair<string, FileAttributes> file in fileSystemChildren)
  172. {
  173. // Folders
  174. if (file.Value.HasFlag(FileAttributes.Directory))
  175. {
  176. returnFiles.Add(file);
  177. }
  178. // If it's a shortcut, resolve it
  179. else if (Shortcut.IsShortcut(file.Key))
  180. {
  181. string newPath = Shortcut.ResolveShortcut(file.Key);
  182. FileAttributes newPathAttributes = File.GetAttributes(newPath);
  183. // Find out if the shortcut is pointing to a directory or file
  184. if (newPathAttributes.HasFlag(FileAttributes.Directory))
  185. {
  186. // If we're flattening then get the shortcut's children
  187. if (flattenShortcuts)
  188. {
  189. IEnumerable<KeyValuePair<string, FileAttributes>> newChildren = Directory.GetFileSystemEntries(newPath, "*", SearchOption.TopDirectoryOnly).Select(f => new KeyValuePair<string, FileAttributes>(f, File.GetAttributes(f)));
  190. returnFiles.AddRange(FilterChildFileSystemEntries(newChildren, false));
  191. }
  192. else
  193. {
  194. returnFiles.Add(new KeyValuePair<string, FileAttributes>(newPath, newPathAttributes));
  195. }
  196. }
  197. else
  198. {
  199. returnFiles.Add(new KeyValuePair<string, FileAttributes>(newPath, newPathAttributes));
  200. }
  201. }
  202. else
  203. {
  204. returnFiles.Add(file);
  205. }
  206. }
  207. return returnFiles;
  208. }
  209. /// <summary>
  210. /// Gets a Person
  211. /// </summary>
  212. public async Task<Person> GetPerson(string name)
  213. {
  214. string path = Path.Combine(Kernel.Instance.ApplicationPaths.PeoplePath, name);
  215. return await GetImagesByNameItem<Person>(path, name);
  216. }
  217. /// <summary>
  218. /// Gets a Studio
  219. /// </summary>
  220. public async Task<Studio> GetStudio(string name)
  221. {
  222. string path = Path.Combine(Kernel.Instance.ApplicationPaths.StudioPath, name);
  223. return await GetImagesByNameItem<Studio>(path, name);
  224. }
  225. /// <summary>
  226. /// Gets a Genre
  227. /// </summary>
  228. public async Task<Genre> GetGenre(string name)
  229. {
  230. string path = Path.Combine(Kernel.Instance.ApplicationPaths.GenrePath, name);
  231. return await GetImagesByNameItem<Genre>(path, name);
  232. }
  233. /// <summary>
  234. /// Gets a Year
  235. /// </summary>
  236. public async Task<Year> GetYear(int value)
  237. {
  238. string path = Path.Combine(Kernel.Instance.ApplicationPaths.YearPath, value.ToString());
  239. return await GetImagesByNameItem<Year>(path, value.ToString());
  240. }
  241. private ConcurrentDictionary<string, object> ImagesByNameItemCache = new ConcurrentDictionary<string, object>();
  242. /// <summary>
  243. /// Generically retrieves an IBN item
  244. /// </summary>
  245. private async Task<T> GetImagesByNameItem<T>(string path, string name)
  246. where T : BaseEntity, new()
  247. {
  248. string key = path.ToLower();
  249. // Look for it in the cache, if it's not there, create it
  250. if (!ImagesByNameItemCache.ContainsKey(key))
  251. {
  252. T obj = await CreateImagesByNameItem<T>(path, name);
  253. ImagesByNameItemCache[key] = obj;
  254. return obj;
  255. }
  256. return ImagesByNameItemCache[key] as T;
  257. }
  258. /// <summary>
  259. /// Creates an IBN item based on a given path
  260. /// </summary>
  261. private async Task<T> CreateImagesByNameItem<T>(string path, string name)
  262. where T : BaseEntity, new()
  263. {
  264. T item = new T();
  265. item.Name = name;
  266. item.Id = Kernel.GetMD5(path);
  267. if (!Directory.Exists(path))
  268. {
  269. Directory.CreateDirectory(path);
  270. }
  271. item.DateCreated = Directory.GetCreationTime(path);
  272. item.DateModified = Directory.GetLastAccessTime(path);
  273. ItemResolveEventArgs args = new ItemResolveEventArgs();
  274. args.Path = path;
  275. args.FileAttributes = File.GetAttributes(path);
  276. args.FileSystemChildren = Directory.GetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly).Select(f => new KeyValuePair<string, FileAttributes>(f, File.GetAttributes(f)));
  277. await Kernel.Instance.ExecuteMetadataProviders(item, args);
  278. return item;
  279. }
  280. }
  281. }