ItemController.cs 11 KB

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