ItemController.cs 11 KB

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