Kernel.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 genre and are allowed for the current user
  256. /// </summary>
  257. public IEnumerable<BaseItem> GetItemsWithGenre(Folder parent, string genre, Guid userId)
  258. {
  259. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.Genres != null && f.Genres.Any(s => s.Equals(genre, StringComparison.OrdinalIgnoreCase)));
  260. }
  261. /// <summary>
  262. /// Finds all recursive items within a top-level parent that contain the given year and are allowed for the current user
  263. /// </summary>
  264. public IEnumerable<BaseItem> GetItemsWithYear(Folder parent, int year, Guid userId)
  265. {
  266. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.ProductionYear.HasValue && f.ProductionYear == year);
  267. }
  268. /// <summary>
  269. /// Finds all recursive items within a top-level parent that contain the given person and are allowed for the current user
  270. /// </summary>
  271. public IEnumerable<BaseItem> GetItemsWithPerson(Folder parent, string personName, Guid userId)
  272. {
  273. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.People != null && f.People.Any(s => s.Name.Equals(personName, StringComparison.OrdinalIgnoreCase)));
  274. }
  275. /// <summary>
  276. /// Gets all years from all recursive children of a folder
  277. /// The CategoryInfo class is used to keep track of the number of times each year appears
  278. /// </summary>
  279. public IEnumerable<CategoryInfo<Year>> GetAllYears(Folder parent, Guid userId)
  280. {
  281. Dictionary<int, int> data = new Dictionary<int, int>();
  282. // Get all the allowed recursive children
  283. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  284. foreach (var item in allItems)
  285. {
  286. // Add the year from the item to the data dictionary
  287. // If the year already exists, increment the count
  288. if (item.ProductionYear == null)
  289. {
  290. continue;
  291. }
  292. if (!data.ContainsKey(item.ProductionYear.Value))
  293. {
  294. data.Add(item.ProductionYear.Value, 1);
  295. }
  296. else
  297. {
  298. data[item.ProductionYear.Value]++;
  299. }
  300. }
  301. // Now go through the dictionary and create a Category for each studio
  302. List<CategoryInfo<Year>> list = new List<CategoryInfo<Year>>();
  303. foreach (int key in data.Keys)
  304. {
  305. // Get the original entity so that we can also supply the PrimaryImagePath
  306. Year entity = Kernel.Instance.ItemController.GetYear(key);
  307. if (entity != null)
  308. {
  309. list.Add(new CategoryInfo<Year>()
  310. {
  311. Item = entity,
  312. ItemCount = data[key]
  313. });
  314. }
  315. }
  316. return list;
  317. }
  318. /// <summary>
  319. /// Gets all studios from all recursive children of a folder
  320. /// The CategoryInfo class is used to keep track of the number of times each studio appears
  321. /// </summary>
  322. public IEnumerable<CategoryInfo<Studio>> GetAllStudios(Folder parent, Guid userId)
  323. {
  324. Dictionary<string, int> data = new Dictionary<string, int>();
  325. // Get all the allowed recursive children
  326. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  327. foreach (var item in allItems)
  328. {
  329. // Add each studio from the item to the data dictionary
  330. // If the studio already exists, increment the count
  331. if (item.Studios == null)
  332. {
  333. continue;
  334. }
  335. foreach (string val in item.Studios)
  336. {
  337. if (!data.ContainsKey(val))
  338. {
  339. data.Add(val, 1);
  340. }
  341. else
  342. {
  343. data[val]++;
  344. }
  345. }
  346. }
  347. // Now go through the dictionary and create a Category for each studio
  348. List<CategoryInfo<Studio>> list = new List<CategoryInfo<Studio>>();
  349. foreach (string key in data.Keys)
  350. {
  351. // Get the original entity so that we can also supply the PrimaryImagePath
  352. Studio entity = Kernel.Instance.ItemController.GetStudio(key);
  353. if (entity != null)
  354. {
  355. list.Add(new CategoryInfo<Studio>()
  356. {
  357. Item = entity,
  358. ItemCount = data[key]
  359. });
  360. }
  361. }
  362. return list;
  363. }
  364. /// <summary>
  365. /// Gets all genres from all recursive children of a folder
  366. /// The CategoryInfo class is used to keep track of the number of times each genres appears
  367. /// </summary>
  368. public IEnumerable<CategoryInfo<Genre>> GetAllGenres(Folder parent, Guid userId)
  369. {
  370. Dictionary<string, int> data = new Dictionary<string, int>();
  371. // Get all the allowed recursive children
  372. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  373. foreach (var item in allItems)
  374. {
  375. // Add each genre from the item to the data dictionary
  376. // If the genre already exists, increment the count
  377. if (item.Genres == null)
  378. {
  379. continue;
  380. }
  381. foreach (string val in item.Genres)
  382. {
  383. if (!data.ContainsKey(val))
  384. {
  385. data.Add(val, 1);
  386. }
  387. else
  388. {
  389. data[val]++;
  390. }
  391. }
  392. }
  393. // Now go through the dictionary and create a Category for each genre
  394. List<CategoryInfo<Genre>> list = new List<CategoryInfo<Genre>>();
  395. foreach (string key in data.Keys)
  396. {
  397. // Get the original entity so that we can also supply the PrimaryImagePath
  398. Genre entity = Kernel.Instance.ItemController.GetGenre(key);
  399. if (entity != null)
  400. {
  401. list.Add(new CategoryInfo<Genre>()
  402. {
  403. Item = entity,
  404. ItemCount = data[key]
  405. });
  406. }
  407. }
  408. return list;
  409. }
  410. /// <summary>
  411. /// Gets all users within the system
  412. /// </summary>
  413. private IEnumerable<User> GetAllUsers()
  414. {
  415. List<User> list = new List<User>();
  416. // Return a dummy user for now since all calls to get items requre a userId
  417. User user = new User();
  418. user.Name = "Default User";
  419. user.Id = Guid.Parse("5d1cf7fce25943b790d140095457a42b");
  420. list.Add(user);
  421. return list;
  422. }
  423. }
  424. }