ItemController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. KeyValuePair<string, WIN32_FIND_DATA>[] 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 KeyValuePair<string, WIN32_FIND_DATA>[] { };
  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, KeyValuePair<string, WIN32_FIND_DATA>[] 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.Key, folder, child.Value);
  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 KeyValuePair<string, WIN32_FIND_DATA>[] FilterChildFileSystemEntries(KeyValuePair<string, WIN32_FIND_DATA>[] fileSystemChildren, bool flattenShortcuts)
  137. {
  138. KeyValuePair<string, WIN32_FIND_DATA>[] returnArray = new KeyValuePair<string, WIN32_FIND_DATA>[fileSystemChildren.Length];
  139. List<KeyValuePair<string, WIN32_FIND_DATA>> resolvedShortcuts = new List<KeyValuePair<string, WIN32_FIND_DATA>>();
  140. for (int i = 0; i < fileSystemChildren.Length; i++)
  141. {
  142. KeyValuePair<string, WIN32_FIND_DATA> file = fileSystemChildren[i];
  143. if (file.Value.IsDirectory)
  144. {
  145. returnArray[i] = file;
  146. }
  147. // If it's a shortcut, resolve it
  148. else if (Shortcut.IsShortcut(file.Key))
  149. {
  150. string newPath = Shortcut.ResolveShortcut(file.Key);
  151. WIN32_FIND_DATA newPathData = FileData.GetFileData(newPath);
  152. // Find out if the shortcut is pointing to a directory or file
  153. if (newPathData.IsDirectory)
  154. {
  155. // If we're flattening then get the shortcut's children
  156. if (flattenShortcuts)
  157. {
  158. returnArray[i] = file;
  159. KeyValuePair<string, WIN32_FIND_DATA>[] newChildren = ConvertFileSystemEntries(Directory.GetFileSystemEntries(newPath, "*", SearchOption.TopDirectoryOnly));
  160. resolvedShortcuts.AddRange(FilterChildFileSystemEntries(newChildren, false));
  161. }
  162. else
  163. {
  164. returnArray[i] = new KeyValuePair<string, WIN32_FIND_DATA>(newPath, newPathData);
  165. }
  166. }
  167. else
  168. {
  169. returnArray[i] = new KeyValuePair<string, WIN32_FIND_DATA>(newPath, newPathData);
  170. }
  171. }
  172. else
  173. {
  174. returnArray[i] = file;
  175. }
  176. }
  177. if (resolvedShortcuts.Count > 0)
  178. {
  179. resolvedShortcuts.InsertRange(0, returnArray);
  180. return resolvedShortcuts.ToArray();
  181. }
  182. else
  183. {
  184. return returnArray;
  185. }
  186. }
  187. /// <summary>
  188. /// Gets a Person
  189. /// </summary>
  190. public async Task<Person> GetPerson(string name)
  191. {
  192. string path = Path.Combine(Kernel.Instance.ApplicationPaths.PeoplePath, name);
  193. return await GetImagesByNameItem<Person>(path, name).ConfigureAwait(false);
  194. }
  195. /// <summary>
  196. /// Gets a Studio
  197. /// </summary>
  198. public async Task<Studio> GetStudio(string name)
  199. {
  200. string path = Path.Combine(Kernel.Instance.ApplicationPaths.StudioPath, name);
  201. return await GetImagesByNameItem<Studio>(path, name).ConfigureAwait(false);
  202. }
  203. /// <summary>
  204. /// Gets a Genre
  205. /// </summary>
  206. public async Task<Genre> GetGenre(string name)
  207. {
  208. string path = Path.Combine(Kernel.Instance.ApplicationPaths.GenrePath, name);
  209. return await GetImagesByNameItem<Genre>(path, name).ConfigureAwait(false);
  210. }
  211. /// <summary>
  212. /// Gets a Year
  213. /// </summary>
  214. public async Task<Year> GetYear(int value)
  215. {
  216. string path = Path.Combine(Kernel.Instance.ApplicationPaths.YearPath, value.ToString());
  217. return await GetImagesByNameItem<Year>(path, value.ToString()).ConfigureAwait(false);
  218. }
  219. private ConcurrentDictionary<string, object> ImagesByNameItemCache = new ConcurrentDictionary<string, object>();
  220. /// <summary>
  221. /// Generically retrieves an IBN item
  222. /// </summary>
  223. private async Task<T> GetImagesByNameItem<T>(string path, string name)
  224. where T : BaseEntity, new()
  225. {
  226. string key = path.ToLower();
  227. // Look for it in the cache, if it's not there, create it
  228. if (!ImagesByNameItemCache.ContainsKey(key))
  229. {
  230. T obj = await CreateImagesByNameItem<T>(path, name).ConfigureAwait(false);
  231. ImagesByNameItemCache[key] = obj;
  232. return obj;
  233. }
  234. return ImagesByNameItemCache[key] as T;
  235. }
  236. /// <summary>
  237. /// Creates an IBN item based on a given path
  238. /// </summary>
  239. private async Task<T> CreateImagesByNameItem<T>(string path, string name)
  240. where T : BaseEntity, new()
  241. {
  242. T item = new T();
  243. item.Name = name;
  244. item.Id = Kernel.GetMD5(path);
  245. if (!Directory.Exists(path))
  246. {
  247. Directory.CreateDirectory(path);
  248. }
  249. item.DateCreated = Directory.GetCreationTime(path);
  250. item.DateModified = Directory.GetLastAccessTime(path);
  251. ItemResolveEventArgs args = new ItemResolveEventArgs();
  252. args.Path = path;
  253. args.FileData = FileData.GetFileData(path);
  254. args.FileSystemChildren = ConvertFileSystemEntries(Directory.GetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly));
  255. await Kernel.Instance.ExecuteMetadataProviders(item, args).ConfigureAwait(false);
  256. return item;
  257. }
  258. private KeyValuePair<string, WIN32_FIND_DATA>[] ConvertFileSystemEntries(string[] files)
  259. {
  260. KeyValuePair<string, WIN32_FIND_DATA>[] items = new KeyValuePair<string, WIN32_FIND_DATA>[files.Length];
  261. for (int i = 0; i < files.Length; i++)
  262. {
  263. string file = files[i];
  264. items[i] = new KeyValuePair<string, WIN32_FIND_DATA>(file, FileData.GetFileData(file));
  265. }
  266. return items;
  267. }
  268. }
  269. }