Kernel.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.Composition;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Common.Kernel;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Events;
  12. using MediaBrowser.Controller.IO;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.Resolvers;
  15. using MediaBrowser.Model.DTO;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.Progress;
  18. using MediaBrowser.Model.Users;
  19. namespace MediaBrowser.Controller
  20. {
  21. public class Kernel : BaseKernel<ServerConfiguration>
  22. {
  23. public static Kernel Instance { get; private set; }
  24. public ItemController ItemController { get; private set; }
  25. public IEnumerable<User> Users { get; private set; }
  26. public Folder RootFolder { get; private set; }
  27. private DirectoryWatchers DirectoryWatchers { get; set; }
  28. private string MediaRootFolderPath
  29. {
  30. get
  31. {
  32. return ApplicationPaths.RootFolderPath;
  33. }
  34. }
  35. /// <summary>
  36. /// Gets the list of currently registered entity resolvers
  37. /// </summary>
  38. [ImportMany(typeof(IBaseItemResolver))]
  39. public IEnumerable<IBaseItemResolver> EntityResolvers { get; private set; }
  40. /// <summary>
  41. /// Creates a kernal based on a Data path, which is akin to our current programdata path
  42. /// </summary>
  43. public Kernel()
  44. : base()
  45. {
  46. Instance = this;
  47. ItemController = new ItemController();
  48. DirectoryWatchers = new DirectoryWatchers();
  49. ItemController.PreBeginResolvePath += ItemController_PreBeginResolvePath;
  50. ItemController.BeginResolvePath += ItemController_BeginResolvePath;
  51. }
  52. public override void Init(IProgress<TaskProgress> progress)
  53. {
  54. base.Init(progress);
  55. progress.Report(new TaskProgress() { Description = "Loading Users", PercentComplete = 15 });
  56. ReloadUsers();
  57. progress.Report(new TaskProgress() { Description = "Loading Media Library", PercentComplete = 20 });
  58. ReloadRoot();
  59. progress.Report(new TaskProgress() { Description = "Loading Complete", PercentComplete = 100 });
  60. }
  61. protected override void OnComposablePartsLoaded()
  62. {
  63. List<IBaseItemResolver> resolvers = EntityResolvers.ToList();
  64. // Add the internal resolvers
  65. resolvers.Add(new VideoResolver());
  66. resolvers.Add(new AudioResolver());
  67. resolvers.Add(new FolderResolver());
  68. EntityResolvers = resolvers;
  69. // The base class will start up all the plugins
  70. base.OnComposablePartsLoaded();
  71. }
  72. /// <summary>
  73. /// Fires when a path is about to be resolved, but before child folders and files
  74. /// have been collected from the file system.
  75. /// This gives us a chance to cancel it if needed, resulting in the path being ignored
  76. /// </summary>
  77. void ItemController_PreBeginResolvePath(object sender, PreBeginResolveEventArgs e)
  78. {
  79. if (e.IsHidden || e.IsSystemFile)
  80. {
  81. // Ignore hidden files and folders
  82. e.Cancel = true;
  83. }
  84. else if (Path.GetFileName(e.Path).Equals("trailers", StringComparison.OrdinalIgnoreCase))
  85. {
  86. // Ignore any folders named "trailers"
  87. e.Cancel = true;
  88. }
  89. }
  90. /// <summary>
  91. /// Fires when a path is about to be resolved, but after child folders and files
  92. /// This gives us a chance to cancel it if needed, resulting in the path being ignored
  93. /// </summary>
  94. void ItemController_BeginResolvePath(object sender, ItemResolveEventArgs e)
  95. {
  96. if (e.IsFolder)
  97. {
  98. if (e.ContainsFile(".ignore"))
  99. {
  100. // Ignore any folders containing a file called .ignore
  101. e.Cancel = true;
  102. }
  103. }
  104. }
  105. private void ReloadUsers()
  106. {
  107. Users = GetAllUsers();
  108. }
  109. /// <summary>
  110. /// Reloads the root media folder
  111. /// </summary>
  112. public void ReloadRoot()
  113. {
  114. if (!Directory.Exists(MediaRootFolderPath))
  115. {
  116. Directory.CreateDirectory(MediaRootFolderPath);
  117. }
  118. DirectoryWatchers.Stop();
  119. RootFolder = ItemController.GetItem(MediaRootFolderPath) as Folder;
  120. DirectoryWatchers.Start();
  121. }
  122. private static MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
  123. public static Guid GetMD5(string str)
  124. {
  125. lock (md5Provider)
  126. {
  127. return new Guid(md5Provider.ComputeHash(Encoding.Unicode.GetBytes(str)));
  128. }
  129. }
  130. public void ReloadItem(BaseItem item)
  131. {
  132. Folder folder = item as Folder;
  133. if (folder != null && folder.IsRoot)
  134. {
  135. ReloadRoot();
  136. }
  137. else
  138. {
  139. if (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  140. {
  141. ReloadItem(item.Parent);
  142. return;
  143. }
  144. BaseItem newItem = ItemController.GetItem(item.Parent, item.Path);
  145. List<BaseItem> children = item.Parent.Children.ToList();
  146. int index = children.IndexOf(item);
  147. children.RemoveAt(index);
  148. children.Insert(index, newItem);
  149. item.Parent.Children = children.ToArray();
  150. }
  151. }
  152. /// <summary>
  153. /// Finds a library item by Id
  154. /// </summary>
  155. public BaseItem GetItemById(Guid id)
  156. {
  157. if (id == Guid.Empty)
  158. {
  159. return RootFolder;
  160. }
  161. return RootFolder.FindById(id);
  162. }
  163. /// <summary>
  164. /// Determines if an item is allowed for a given user
  165. /// </summary>
  166. public bool IsParentalAllowed(BaseItem item, Guid userId)
  167. {
  168. // not yet implemented
  169. return true;
  170. }
  171. /// <summary>
  172. /// Gets allowed children of an item
  173. /// </summary>
  174. public IEnumerable<BaseItem> GetParentalAllowedChildren(Folder folder, Guid userId)
  175. {
  176. return folder.Children.Where(i => IsParentalAllowed(i, userId));
  177. }
  178. /// <summary>
  179. /// Gets allowed recursive children of an item
  180. /// </summary>
  181. public IEnumerable<BaseItem> GetParentalAllowedRecursiveChildren(Folder folder, Guid userId)
  182. {
  183. foreach (var item in GetParentalAllowedChildren(folder, userId))
  184. {
  185. yield return item;
  186. var subFolder = item as Folder;
  187. if (subFolder != null)
  188. {
  189. foreach (var subitem in GetParentalAllowedRecursiveChildren(subFolder, userId))
  190. {
  191. yield return subitem;
  192. }
  193. }
  194. }
  195. }
  196. /// <summary>
  197. /// Gets user data for an item, if there is any
  198. /// </summary>
  199. public UserItemData GetUserItemData(Guid userId, Guid itemId)
  200. {
  201. User user = Users.First(u => u.Id == userId);
  202. if (user.ItemData.ContainsKey(itemId))
  203. {
  204. return user.ItemData[itemId];
  205. }
  206. return null;
  207. }
  208. /// <summary>
  209. /// Gets all recently added items (recursive) within a folder, based on configuration and parental settings
  210. /// </summary>
  211. public IEnumerable<BaseItem> GetRecentlyAddedItems(Folder parent, Guid userId)
  212. {
  213. DateTime now = DateTime.Now;
  214. User user = Users.First(u => u.Id == userId);
  215. return GetParentalAllowedRecursiveChildren(parent, userId).Where(i => !(i is Folder) && (now - i.DateCreated).TotalDays < user.RecentItemDays);
  216. }
  217. /// <summary>
  218. /// Gets all recently added unplayed items (recursive) within a folder, based on configuration and parental settings
  219. /// </summary>
  220. public IEnumerable<BaseItem> GetRecentlyAddedUnplayedItems(Folder parent, Guid userId)
  221. {
  222. return GetRecentlyAddedItems(parent, userId).Where(i =>
  223. {
  224. var userdata = GetUserItemData(userId, i.Id);
  225. return userdata == null || userdata.PlayCount == 0;
  226. });
  227. }
  228. /// <summary>
  229. /// Gets all in-progress items (recursive) within a folder
  230. /// </summary>
  231. public IEnumerable<BaseItem> GetInProgressItems(Folder parent, Guid userId)
  232. {
  233. return GetParentalAllowedRecursiveChildren(parent, userId).Where(i =>
  234. {
  235. if (i is Folder)
  236. {
  237. return false;
  238. }
  239. var userdata = GetUserItemData(userId, i.Id);
  240. return userdata != null && userdata.PlaybackPosition.Ticks > 0;
  241. });
  242. }
  243. /// <summary>
  244. /// Finds all recursive items within a top-level parent that contain the given studio and are allowed for the current user
  245. /// </summary>
  246. public IEnumerable<BaseItem> GetItemsWithStudio(Folder parent, string studio, Guid userId)
  247. {
  248. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.Studios != null && f.Studios.Any(s => s.Equals(studio, StringComparison.OrdinalIgnoreCase)));
  249. }
  250. /// <summary>
  251. /// Finds all recursive items within a top-level parent that contain the given person and are allowed for the current user
  252. /// </summary>
  253. /// <param name="personType">Specify this to limit results to a specific PersonType</param>
  254. public IEnumerable<BaseItem> GetItemsWithPerson(Folder parent, string person, PersonType? personType, Guid userId)
  255. {
  256. return GetParentalAllowedRecursiveChildren(parent, userId).Where(c =>
  257. {
  258. if (c.People != null)
  259. {
  260. if (personType.HasValue)
  261. {
  262. return c.People.Any(p => p.Name.Equals(person, StringComparison.OrdinalIgnoreCase) && p.PersonType == personType.Value);
  263. }
  264. else
  265. {
  266. return c.People.Any(p => p.Name.Equals(person, StringComparison.OrdinalIgnoreCase));
  267. }
  268. }
  269. return false;
  270. });
  271. }
  272. /// <summary>
  273. /// Finds all recursive items within a top-level parent that contain the given genre and are allowed for the current user
  274. /// </summary>
  275. public IEnumerable<BaseItem> GetItemsWithGenre(Folder parent, string genre, Guid userId)
  276. {
  277. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.Genres != null && f.Genres.Any(s => s.Equals(genre, StringComparison.OrdinalIgnoreCase)));
  278. }
  279. /// <summary>
  280. /// Finds all recursive items within a top-level parent that contain the given year and are allowed for the current user
  281. /// </summary>
  282. public IEnumerable<BaseItem> GetItemsWithYear(Folder parent, int year, Guid userId)
  283. {
  284. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.ProductionYear.HasValue && f.ProductionYear == year);
  285. }
  286. /// <summary>
  287. /// Finds all recursive items within a top-level parent that contain the given person and are allowed for the current user
  288. /// </summary>
  289. public IEnumerable<BaseItem> GetItemsWithPerson(Folder parent, string personName, Guid userId)
  290. {
  291. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.People != null && f.People.Any(s => s.Name.Equals(personName, StringComparison.OrdinalIgnoreCase)));
  292. }
  293. /// <summary>
  294. /// Gets all years from all recursive children of a folder
  295. /// The CategoryInfo class is used to keep track of the number of times each year appears
  296. /// </summary>
  297. public IEnumerable<IBNItem<Year>> GetAllYears(Folder parent, Guid userId)
  298. {
  299. Dictionary<int, int> data = new Dictionary<int, int>();
  300. // Get all the allowed recursive children
  301. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  302. foreach (var item in allItems)
  303. {
  304. // Add the year from the item to the data dictionary
  305. // If the year already exists, increment the count
  306. if (item.ProductionYear == null)
  307. {
  308. continue;
  309. }
  310. if (!data.ContainsKey(item.ProductionYear.Value))
  311. {
  312. data.Add(item.ProductionYear.Value, 1);
  313. }
  314. else
  315. {
  316. data[item.ProductionYear.Value]++;
  317. }
  318. }
  319. // Now go through the dictionary and create a Category for each studio
  320. List<IBNItem<Year>> list = new List<IBNItem<Year>>();
  321. foreach (int key in data.Keys)
  322. {
  323. // Get the original entity so that we can also supply the PrimaryImagePath
  324. Year entity = Kernel.Instance.ItemController.GetYear(key);
  325. if (entity != null)
  326. {
  327. list.Add(new IBNItem<Year>()
  328. {
  329. Item = entity,
  330. BaseItemCount = data[key]
  331. });
  332. }
  333. }
  334. return list;
  335. }
  336. /// <summary>
  337. /// Gets all studios from all recursive children of a folder
  338. /// The CategoryInfo class is used to keep track of the number of times each studio appears
  339. /// </summary>
  340. public IEnumerable<IBNItem<Studio>> GetAllStudios(Folder parent, Guid userId)
  341. {
  342. Dictionary<string, int> data = new Dictionary<string, int>();
  343. // Get all the allowed recursive children
  344. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  345. foreach (var item in allItems)
  346. {
  347. // Add each studio from the item to the data dictionary
  348. // If the studio already exists, increment the count
  349. if (item.Studios == null)
  350. {
  351. continue;
  352. }
  353. foreach (string val in item.Studios)
  354. {
  355. if (!data.ContainsKey(val))
  356. {
  357. data.Add(val, 1);
  358. }
  359. else
  360. {
  361. data[val]++;
  362. }
  363. }
  364. }
  365. // Now go through the dictionary and create a Category for each studio
  366. List<IBNItem<Studio>> list = new List<IBNItem<Studio>>();
  367. foreach (string key in data.Keys)
  368. {
  369. // Get the original entity so that we can also supply the PrimaryImagePath
  370. Studio entity = Kernel.Instance.ItemController.GetStudio(key);
  371. if (entity != null)
  372. {
  373. list.Add(new IBNItem<Studio>()
  374. {
  375. Item = entity,
  376. BaseItemCount = data[key]
  377. });
  378. }
  379. }
  380. return list;
  381. }
  382. /// <summary>
  383. /// Gets all genres from all recursive children of a folder
  384. /// The CategoryInfo class is used to keep track of the number of times each genres appears
  385. /// </summary>
  386. public IEnumerable<IBNItem<Genre>> GetAllGenres(Folder parent, Guid userId)
  387. {
  388. Dictionary<string, int> data = new Dictionary<string, int>();
  389. // Get all the allowed recursive children
  390. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  391. foreach (var item in allItems)
  392. {
  393. // Add each genre from the item to the data dictionary
  394. // If the genre already exists, increment the count
  395. if (item.Genres == null)
  396. {
  397. continue;
  398. }
  399. foreach (string val in item.Genres)
  400. {
  401. if (!data.ContainsKey(val))
  402. {
  403. data.Add(val, 1);
  404. }
  405. else
  406. {
  407. data[val]++;
  408. }
  409. }
  410. }
  411. // Now go through the dictionary and create a Category for each genre
  412. List<IBNItem<Genre>> list = new List<IBNItem<Genre>>();
  413. foreach (string key in data.Keys)
  414. {
  415. // Get the original entity so that we can also supply the PrimaryImagePath
  416. Genre entity = Kernel.Instance.ItemController.GetGenre(key);
  417. if (entity != null)
  418. {
  419. list.Add(new IBNItem<Genre>()
  420. {
  421. Item = entity,
  422. BaseItemCount = data[key]
  423. });
  424. }
  425. }
  426. return list;
  427. }
  428. /// <summary>
  429. /// Gets all users within the system
  430. /// </summary>
  431. private IEnumerable<User> GetAllUsers()
  432. {
  433. List<User> list = new List<User>();
  434. // Return a dummy user for now since all calls to get items requre a userId
  435. User user = new User();
  436. user.Name = "Default User";
  437. user.Id = Guid.Parse("5d1cf7fce25943b790d140095457a42b");
  438. list.Add(user);
  439. return list;
  440. }
  441. }
  442. }