Kernel.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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 person and are allowed for the current user
  263. /// </summary>
  264. public IEnumerable<BaseItem> GetItemsWithPerson(Folder parent, string personName, Guid userId)
  265. {
  266. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.People != null && f.People.Any(s => s.Name.Equals(personName, StringComparison.OrdinalIgnoreCase)));
  267. }
  268. /// <summary>
  269. /// Gets all studios from all recursive children of a folder
  270. /// The CategoryInfo class is used to keep track of the number of times each studio appears
  271. /// </summary>
  272. public IEnumerable<CategoryInfo<Studio>> GetAllStudios(Folder parent, Guid userId)
  273. {
  274. Dictionary<string, int> data = new Dictionary<string, int>();
  275. // Get all the allowed recursive children
  276. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  277. foreach (var item in allItems)
  278. {
  279. // Add each studio from the item to the data dictionary
  280. // If the studio already exists, increment the count
  281. if (item.Studios == null)
  282. {
  283. continue;
  284. }
  285. foreach (string val in item.Studios)
  286. {
  287. if (!data.ContainsKey(val))
  288. {
  289. data.Add(val, 1);
  290. }
  291. else
  292. {
  293. data[val]++;
  294. }
  295. }
  296. }
  297. // Now go through the dictionary and create a Category for each studio
  298. List<CategoryInfo<Studio>> list = new List<CategoryInfo<Studio>>();
  299. foreach (string key in data.Keys)
  300. {
  301. // Get the original entity so that we can also supply the PrimaryImagePath
  302. Studio entity = Kernel.Instance.ItemController.GetStudio(key);
  303. if (entity != null)
  304. {
  305. list.Add(new CategoryInfo<Studio>()
  306. {
  307. Item = entity,
  308. ItemCount = data[key]
  309. });
  310. }
  311. }
  312. return list;
  313. }
  314. /// <summary>
  315. /// Gets all genres from all recursive children of a folder
  316. /// The CategoryInfo class is used to keep track of the number of times each genres appears
  317. /// </summary>
  318. public IEnumerable<CategoryInfo<Genre>> GetAllGenres(Folder parent, Guid userId)
  319. {
  320. Dictionary<string, int> data = new Dictionary<string, int>();
  321. // Get all the allowed recursive children
  322. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  323. foreach (var item in allItems)
  324. {
  325. // Add each genre from the item to the data dictionary
  326. // If the genre already exists, increment the count
  327. if (item.Genres == null)
  328. {
  329. continue;
  330. }
  331. foreach (string val in item.Genres)
  332. {
  333. if (!data.ContainsKey(val))
  334. {
  335. data.Add(val, 1);
  336. }
  337. else
  338. {
  339. data[val]++;
  340. }
  341. }
  342. }
  343. // Now go through the dictionary and create a Category for each genre
  344. List<CategoryInfo<Genre>> list = new List<CategoryInfo<Genre>>();
  345. foreach (string key in data.Keys)
  346. {
  347. // Get the original entity so that we can also supply the PrimaryImagePath
  348. Genre entity = Kernel.Instance.ItemController.GetGenre(key);
  349. if (entity != null)
  350. {
  351. list.Add(new CategoryInfo<Genre>()
  352. {
  353. Item = entity,
  354. ItemCount = data[key]
  355. });
  356. }
  357. }
  358. return list;
  359. }
  360. /// <summary>
  361. /// Gets all users within the system
  362. /// </summary>
  363. private IEnumerable<User> GetAllUsers()
  364. {
  365. List<User> list = new List<User>();
  366. // Return a dummy user for now since all calls to get items requre a userId
  367. User user = new User();
  368. user.Name = "Default User";
  369. user.Id = Guid.NewGuid();
  370. list.Add(user);
  371. return list;
  372. }
  373. }
  374. }