ItemController.cs 13 KB

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