Kernel.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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.Configuration;
  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 UserConfiguration GetUserConfiguration(Guid userId)
  131. {
  132. return Configuration.DefaultUserConfiguration;
  133. }
  134. public void ReloadItem(BaseItem item)
  135. {
  136. Folder folder = item as Folder;
  137. if (folder != null && folder.IsRoot)
  138. {
  139. ReloadRoot();
  140. }
  141. else
  142. {
  143. if (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  144. {
  145. ReloadItem(item.Parent);
  146. return;
  147. }
  148. BaseItem newItem = ItemController.GetItem(item.Parent, item.Path);
  149. List<BaseItem> children = item.Parent.Children.ToList();
  150. int index = children.IndexOf(item);
  151. children.RemoveAt(index);
  152. children.Insert(index, newItem);
  153. item.Parent.Children = children.ToArray();
  154. }
  155. }
  156. /// <summary>
  157. /// Finds a library item by Id
  158. /// </summary>
  159. public BaseItem GetItemById(Guid id)
  160. {
  161. if (id == Guid.Empty)
  162. {
  163. return RootFolder;
  164. }
  165. return RootFolder.FindById(id);
  166. }
  167. /// <summary>
  168. /// Determines if an item is allowed for a given user
  169. /// </summary>
  170. public bool IsParentalAllowed(BaseItem item, Guid userId)
  171. {
  172. // not yet implemented
  173. return true;
  174. }
  175. /// <summary>
  176. /// Gets allowed children of an item
  177. /// </summary>
  178. public IEnumerable<BaseItem> GetParentalAllowedChildren(Folder folder, Guid userId)
  179. {
  180. return folder.Children.Where(i => IsParentalAllowed(i, userId));
  181. }
  182. /// <summary>
  183. /// Gets allowed recursive children of an item
  184. /// </summary>
  185. public IEnumerable<BaseItem> GetParentalAllowedRecursiveChildren(Folder folder, Guid userId)
  186. {
  187. foreach (var item in GetParentalAllowedChildren(folder, userId))
  188. {
  189. yield return item;
  190. var subFolder = item as Folder;
  191. if (subFolder != null)
  192. {
  193. foreach (var subitem in GetParentalAllowedRecursiveChildren(subFolder, userId))
  194. {
  195. yield return subitem;
  196. }
  197. }
  198. }
  199. }
  200. /// <summary>
  201. /// Gets user data for an item, if there is any
  202. /// </summary>
  203. public UserItemData GetUserItemData(Guid userId, Guid itemId)
  204. {
  205. User user = Users.First(u => u.Id == userId);
  206. if (user.ItemData.ContainsKey(itemId))
  207. {
  208. return user.ItemData[itemId];
  209. }
  210. return null;
  211. }
  212. /// <summary>
  213. /// Gets all recently added items (recursive) within a folder, based on configuration and parental settings
  214. /// </summary>
  215. public IEnumerable<BaseItem> GetRecentlyAddedItems(Folder parent, Guid userId)
  216. {
  217. DateTime now = DateTime.Now;
  218. UserConfiguration config = GetUserConfiguration(userId);
  219. return GetParentalAllowedRecursiveChildren(parent, userId).Where(i => !(i is Folder) && (now - i.DateCreated).TotalDays < config.RecentItemDays);
  220. }
  221. /// <summary>
  222. /// Gets all recently added unplayed items (recursive) within a folder, based on configuration and parental settings
  223. /// </summary>
  224. public IEnumerable<BaseItem> GetRecentlyAddedUnplayedItems(Folder parent, Guid userId)
  225. {
  226. return GetRecentlyAddedItems(parent, userId).Where(i =>
  227. {
  228. var userdata = GetUserItemData(userId, i.Id);
  229. return userdata == null || userdata.PlayCount == 0;
  230. });
  231. }
  232. /// <summary>
  233. /// Gets all in-progress items (recursive) within a folder
  234. /// </summary>
  235. public IEnumerable<BaseItem> GetInProgressItems(Folder parent, Guid userId)
  236. {
  237. return GetParentalAllowedRecursiveChildren(parent, userId).Where(i =>
  238. {
  239. if (i is Folder)
  240. {
  241. return false;
  242. }
  243. var userdata = GetUserItemData(userId, i.Id);
  244. return userdata != null && userdata.PlaybackPosition.Ticks > 0;
  245. });
  246. }
  247. /// <summary>
  248. /// Finds all recursive items within a top-level parent that contain the given studio and are allowed for the current user
  249. /// </summary>
  250. public IEnumerable<BaseItem> GetItemsWithStudio(Folder parent, string studio, Guid userId)
  251. {
  252. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.Studios != null && f.Studios.Any(s => s.Equals(studio, StringComparison.OrdinalIgnoreCase)));
  253. }
  254. /// <summary>
  255. /// Finds all recursive items within a top-level parent that contain the given person and are allowed for the current user
  256. /// </summary>
  257. /// <param name="personType">Specify this to limit results to a specific PersonType</param>
  258. public IEnumerable<BaseItem> GetItemsWithPerson(Folder parent, string person, PersonType? personType, Guid userId)
  259. {
  260. return GetParentalAllowedRecursiveChildren(parent, userId).Where(c =>
  261. {
  262. if (c.People != null)
  263. {
  264. if (personType.HasValue)
  265. {
  266. return c.People.Any(p => p.Name.Equals(person, StringComparison.OrdinalIgnoreCase) && p.PersonType == personType.Value);
  267. }
  268. else
  269. {
  270. return c.People.Any(p => p.Name.Equals(person, StringComparison.OrdinalIgnoreCase));
  271. }
  272. }
  273. return false;
  274. });
  275. }
  276. /// <summary>
  277. /// Finds all recursive items within a top-level parent that contain the given genre and are allowed for the current user
  278. /// </summary>
  279. public IEnumerable<BaseItem> GetItemsWithGenre(Folder parent, string genre, Guid userId)
  280. {
  281. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.Genres != null && f.Genres.Any(s => s.Equals(genre, StringComparison.OrdinalIgnoreCase)));
  282. }
  283. /// <summary>
  284. /// Finds all recursive items within a top-level parent that contain the given year and are allowed for the current user
  285. /// </summary>
  286. public IEnumerable<BaseItem> GetItemsWithYear(Folder parent, int year, Guid userId)
  287. {
  288. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.ProductionYear.HasValue && f.ProductionYear == year);
  289. }
  290. /// <summary>
  291. /// Finds all recursive items within a top-level parent that contain the given person and are allowed for the current user
  292. /// </summary>
  293. public IEnumerable<BaseItem> GetItemsWithPerson(Folder parent, string personName, Guid userId)
  294. {
  295. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.People != null && f.People.Any(s => s.Name.Equals(personName, StringComparison.OrdinalIgnoreCase)));
  296. }
  297. /// <summary>
  298. /// Gets all years from all recursive children of a folder
  299. /// The CategoryInfo class is used to keep track of the number of times each year appears
  300. /// </summary>
  301. public IEnumerable<CategoryInfo<Year>> GetAllYears(Folder parent, Guid userId)
  302. {
  303. Dictionary<int, int> data = new Dictionary<int, int>();
  304. // Get all the allowed recursive children
  305. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  306. foreach (var item in allItems)
  307. {
  308. // Add the year from the item to the data dictionary
  309. // If the year already exists, increment the count
  310. if (item.ProductionYear == null)
  311. {
  312. continue;
  313. }
  314. if (!data.ContainsKey(item.ProductionYear.Value))
  315. {
  316. data.Add(item.ProductionYear.Value, 1);
  317. }
  318. else
  319. {
  320. data[item.ProductionYear.Value]++;
  321. }
  322. }
  323. // Now go through the dictionary and create a Category for each studio
  324. List<CategoryInfo<Year>> list = new List<CategoryInfo<Year>>();
  325. foreach (int key in data.Keys)
  326. {
  327. // Get the original entity so that we can also supply the PrimaryImagePath
  328. Year entity = Kernel.Instance.ItemController.GetYear(key);
  329. if (entity != null)
  330. {
  331. list.Add(new CategoryInfo<Year>()
  332. {
  333. Item = entity,
  334. ItemCount = data[key]
  335. });
  336. }
  337. }
  338. return list;
  339. }
  340. /// <summary>
  341. /// Gets all studios from all recursive children of a folder
  342. /// The CategoryInfo class is used to keep track of the number of times each studio appears
  343. /// </summary>
  344. public IEnumerable<CategoryInfo<Studio>> GetAllStudios(Folder parent, Guid userId)
  345. {
  346. Dictionary<string, int> data = new Dictionary<string, int>();
  347. // Get all the allowed recursive children
  348. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  349. foreach (var item in allItems)
  350. {
  351. // Add each studio from the item to the data dictionary
  352. // If the studio already exists, increment the count
  353. if (item.Studios == null)
  354. {
  355. continue;
  356. }
  357. foreach (string val in item.Studios)
  358. {
  359. if (!data.ContainsKey(val))
  360. {
  361. data.Add(val, 1);
  362. }
  363. else
  364. {
  365. data[val]++;
  366. }
  367. }
  368. }
  369. // Now go through the dictionary and create a Category for each studio
  370. List<CategoryInfo<Studio>> list = new List<CategoryInfo<Studio>>();
  371. foreach (string key in data.Keys)
  372. {
  373. // Get the original entity so that we can also supply the PrimaryImagePath
  374. Studio entity = Kernel.Instance.ItemController.GetStudio(key);
  375. if (entity != null)
  376. {
  377. list.Add(new CategoryInfo<Studio>()
  378. {
  379. Item = entity,
  380. ItemCount = data[key]
  381. });
  382. }
  383. }
  384. return list;
  385. }
  386. /// <summary>
  387. /// Gets all genres from all recursive children of a folder
  388. /// The CategoryInfo class is used to keep track of the number of times each genres appears
  389. /// </summary>
  390. public IEnumerable<CategoryInfo<Genre>> GetAllGenres(Folder parent, Guid userId)
  391. {
  392. Dictionary<string, int> data = new Dictionary<string, int>();
  393. // Get all the allowed recursive children
  394. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  395. foreach (var item in allItems)
  396. {
  397. // Add each genre from the item to the data dictionary
  398. // If the genre already exists, increment the count
  399. if (item.Genres == null)
  400. {
  401. continue;
  402. }
  403. foreach (string val in item.Genres)
  404. {
  405. if (!data.ContainsKey(val))
  406. {
  407. data.Add(val, 1);
  408. }
  409. else
  410. {
  411. data[val]++;
  412. }
  413. }
  414. }
  415. // Now go through the dictionary and create a Category for each genre
  416. List<CategoryInfo<Genre>> list = new List<CategoryInfo<Genre>>();
  417. foreach (string key in data.Keys)
  418. {
  419. // Get the original entity so that we can also supply the PrimaryImagePath
  420. Genre entity = Kernel.Instance.ItemController.GetGenre(key);
  421. if (entity != null)
  422. {
  423. list.Add(new CategoryInfo<Genre>()
  424. {
  425. Item = entity,
  426. ItemCount = data[key]
  427. });
  428. }
  429. }
  430. return list;
  431. }
  432. /// <summary>
  433. /// Gets all users within the system
  434. /// </summary>
  435. private IEnumerable<User> GetAllUsers()
  436. {
  437. List<User> list = new List<User>();
  438. // Return a dummy user for now since all calls to get items requre a userId
  439. User user = new User();
  440. user.Name = "Default User";
  441. user.Id = Guid.Parse("5d1cf7fce25943b790d140095457a42b");
  442. list.Add(user);
  443. return list;
  444. }
  445. }
  446. }