Kernel.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 System.Threading.Tasks;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Common.Kernel;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Controller.Events;
  13. using MediaBrowser.Controller.IO;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.Resolvers;
  16. using MediaBrowser.Model.Configuration;
  17. using MediaBrowser.Model.Entities;
  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. protected override void OnComposablePartsLoaded()
  53. {
  54. List<IBaseItemResolver> resolvers = EntityResolvers.ToList();
  55. // Add the internal resolvers
  56. resolvers.Add(new VideoResolver());
  57. resolvers.Add(new AudioResolver());
  58. resolvers.Add(new FolderResolver());
  59. EntityResolvers = resolvers;
  60. // The base class will start up all the plugins
  61. base.OnComposablePartsLoaded();
  62. // Get users from users folder
  63. // Load root media folder
  64. Parallel.Invoke(ReloadUsers, ReloadRoot);
  65. }
  66. /// <summary>
  67. /// Fires when a path is about to be resolved, but before child folders and files
  68. /// have been collected from the file system.
  69. /// This gives us a chance to cancel it if needed, resulting in the path being ignored
  70. /// </summary>
  71. void ItemController_PreBeginResolvePath(object sender, PreBeginResolveEventArgs e)
  72. {
  73. if (e.IsHidden || e.IsSystemFile)
  74. {
  75. // Ignore hidden files and folders
  76. e.Cancel = true;
  77. }
  78. else if (Path.GetFileName(e.Path).Equals("trailers", StringComparison.OrdinalIgnoreCase))
  79. {
  80. // Ignore any folders named "trailers"
  81. e.Cancel = true;
  82. }
  83. }
  84. /// <summary>
  85. /// Fires when a path is about to be resolved, but after child folders and files
  86. /// This gives us a chance to cancel it if needed, resulting in the path being ignored
  87. /// </summary>
  88. void ItemController_BeginResolvePath(object sender, ItemResolveEventArgs e)
  89. {
  90. if (e.IsFolder)
  91. {
  92. if (e.ContainsFile(".ignore"))
  93. {
  94. // Ignore any folders containing a file called .ignore
  95. e.Cancel = true;
  96. }
  97. }
  98. }
  99. private void ReloadUsers()
  100. {
  101. Users = GetAllUsers();
  102. }
  103. /// <summary>
  104. /// Reloads the root media folder
  105. /// </summary>
  106. public void ReloadRoot()
  107. {
  108. if (!Directory.Exists(MediaRootFolderPath))
  109. {
  110. Directory.CreateDirectory(MediaRootFolderPath);
  111. }
  112. DirectoryWatchers.Stop();
  113. RootFolder = ItemController.GetItem(MediaRootFolderPath) as Folder;
  114. DirectoryWatchers.Start();
  115. }
  116. private static MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
  117. public static Guid GetMD5(string str)
  118. {
  119. lock (md5Provider)
  120. {
  121. return new Guid(md5Provider.ComputeHash(Encoding.Unicode.GetBytes(str)));
  122. }
  123. }
  124. public UserConfiguration GetUserConfiguration(Guid userId)
  125. {
  126. return Configuration.DefaultUserConfiguration;
  127. }
  128. public void ReloadItem(BaseItem item)
  129. {
  130. Folder folder = item as Folder;
  131. if (folder != null && folder.IsRoot)
  132. {
  133. ReloadRoot();
  134. }
  135. else
  136. {
  137. if (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  138. {
  139. ReloadItem(item.Parent);
  140. return;
  141. }
  142. BaseItem newItem = ItemController.GetItem(item.Parent, item.Path);
  143. List<BaseItem> children = item.Parent.Children.ToList();
  144. int index = children.IndexOf(item);
  145. children.RemoveAt(index);
  146. children.Insert(index, newItem);
  147. item.Parent.Children = children.ToArray();
  148. }
  149. }
  150. /// <summary>
  151. /// Finds a library item by Id
  152. /// </summary>
  153. public BaseItem GetItemById(Guid id)
  154. {
  155. if (id == Guid.Empty)
  156. {
  157. return RootFolder;
  158. }
  159. return RootFolder.FindById(id);
  160. }
  161. /// <summary>
  162. /// Determines if an item is allowed for a given user
  163. /// </summary>
  164. public bool IsParentalAllowed(BaseItem item, Guid userId)
  165. {
  166. // not yet implemented
  167. return true;
  168. }
  169. /// <summary>
  170. /// Gets allowed children of an item
  171. /// </summary>
  172. public IEnumerable<BaseItem> GetParentalAllowedChildren(Folder folder, Guid userId)
  173. {
  174. return folder.Children.Where(i => IsParentalAllowed(i, userId));
  175. }
  176. /// <summary>
  177. /// Gets allowed recursive children of an item
  178. /// </summary>
  179. public IEnumerable<BaseItem> GetParentalAllowedRecursiveChildren(Folder folder, Guid userId)
  180. {
  181. foreach (var item in GetParentalAllowedChildren(folder, userId))
  182. {
  183. yield return item;
  184. var subFolder = item as Folder;
  185. if (subFolder != null)
  186. {
  187. foreach (var subitem in GetParentalAllowedRecursiveChildren(subFolder, userId))
  188. {
  189. yield return subitem;
  190. }
  191. }
  192. }
  193. }
  194. /// <summary>
  195. /// Gets user data for an item, if there is any
  196. /// </summary>
  197. public UserItemData GetUserItemData(Guid userId, Guid itemId)
  198. {
  199. User user = Users.First(u => u.Id == userId);
  200. if (user.ItemData.ContainsKey(itemId))
  201. {
  202. return user.ItemData[itemId];
  203. }
  204. return null;
  205. }
  206. /// <summary>
  207. /// Gets all recently added items (recursive) within a folder, based on configuration and parental settings
  208. /// </summary>
  209. public IEnumerable<BaseItem> GetRecentlyAddedItems(Folder parent, Guid userId)
  210. {
  211. DateTime now = DateTime.Now;
  212. UserConfiguration config = GetUserConfiguration(userId);
  213. return GetParentalAllowedRecursiveChildren(parent, userId).Where(i => !(i is Folder) && (now - i.DateCreated).TotalDays < config.RecentItemDays);
  214. }
  215. /// <summary>
  216. /// Gets all recently added unplayed items (recursive) within a folder, based on configuration and parental settings
  217. /// </summary>
  218. public IEnumerable<BaseItem> GetRecentlyAddedUnplayedItems(Folder parent, Guid userId)
  219. {
  220. return GetRecentlyAddedItems(parent, userId).Where(i =>
  221. {
  222. var userdata = GetUserItemData(userId, i.Id);
  223. return userdata == null || userdata.PlayCount == 0;
  224. });
  225. }
  226. /// <summary>
  227. /// Gets all in-progress items (recursive) within a folder
  228. /// </summary>
  229. public IEnumerable<BaseItem> GetInProgressItems(Folder parent, Guid userId)
  230. {
  231. return GetParentalAllowedRecursiveChildren(parent, userId).Where(i =>
  232. {
  233. if (i is Folder)
  234. {
  235. return false;
  236. }
  237. var userdata = GetUserItemData(userId, i.Id);
  238. return userdata != null && userdata.PlaybackPosition.Ticks > 0;
  239. });
  240. }
  241. /// <summary>
  242. /// Finds all recursive items within a top-level parent that contain the given studio and are allowed for the current user
  243. /// </summary>
  244. public IEnumerable<BaseItem> GetItemsWithStudio(Folder parent, string studio, Guid userId)
  245. {
  246. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.Studios != null && f.Studios.Any(s => s.Equals(studio, StringComparison.OrdinalIgnoreCase)));
  247. }
  248. /// <summary>
  249. /// Finds all recursive items within a top-level parent that contain the given genre and are allowed for the current user
  250. /// </summary>
  251. public IEnumerable<BaseItem> GetItemsWithGenre(Folder parent, string genre, Guid userId)
  252. {
  253. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.Genres != null && f.Genres.Any(s => s.Equals(genre, StringComparison.OrdinalIgnoreCase)));
  254. }
  255. /// <summary>
  256. /// Finds all recursive items within a top-level parent that contain the given person and are allowed for the current user
  257. /// </summary>
  258. public IEnumerable<BaseItem> GetItemsWithPerson(Folder parent, string personName, Guid userId)
  259. {
  260. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.People != null && f.People.Any(s => s.Name.Equals(personName, StringComparison.OrdinalIgnoreCase)));
  261. }
  262. /// <summary>
  263. /// Gets all studios from all recursive children of a folder
  264. /// The CategoryInfo class is used to keep track of the number of times each studio appears
  265. /// </summary>
  266. public IEnumerable<CategoryInfo<Studio>> GetAllStudios(Folder parent, Guid userId)
  267. {
  268. Dictionary<string, int> data = new Dictionary<string, int>();
  269. // Get all the allowed recursive children
  270. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  271. foreach (var item in allItems)
  272. {
  273. // Add each studio from the item to the data dictionary
  274. // If the studio already exists, increment the count
  275. if (item.Studios == null)
  276. {
  277. continue;
  278. }
  279. foreach (string val in item.Studios)
  280. {
  281. if (!data.ContainsKey(val))
  282. {
  283. data.Add(val, 1);
  284. }
  285. else
  286. {
  287. data[val]++;
  288. }
  289. }
  290. }
  291. // Now go through the dictionary and create a Category for each studio
  292. List<CategoryInfo<Studio>> list = new List<CategoryInfo<Studio>>();
  293. foreach (string key in data.Keys)
  294. {
  295. // Get the original entity so that we can also supply the PrimaryImagePath
  296. Studio entity = Kernel.Instance.ItemController.GetStudio(key);
  297. if (entity != null)
  298. {
  299. list.Add(new CategoryInfo<Studio>()
  300. {
  301. Item = entity,
  302. ItemCount = data[key]
  303. });
  304. }
  305. }
  306. return list;
  307. }
  308. /// <summary>
  309. /// Gets all genres from all recursive children of a folder
  310. /// The CategoryInfo class is used to keep track of the number of times each genres appears
  311. /// </summary>
  312. public IEnumerable<CategoryInfo<Genre>> GetAllGenres(Folder parent, Guid userId)
  313. {
  314. Dictionary<string, int> data = new Dictionary<string, int>();
  315. // Get all the allowed recursive children
  316. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  317. foreach (var item in allItems)
  318. {
  319. // Add each genre from the item to the data dictionary
  320. // If the genre already exists, increment the count
  321. if (item.Genres == null)
  322. {
  323. continue;
  324. }
  325. foreach (string val in item.Genres)
  326. {
  327. if (!data.ContainsKey(val))
  328. {
  329. data.Add(val, 1);
  330. }
  331. else
  332. {
  333. data[val]++;
  334. }
  335. }
  336. }
  337. // Now go through the dictionary and create a Category for each genre
  338. List<CategoryInfo<Genre>> list = new List<CategoryInfo<Genre>>();
  339. foreach (string key in data.Keys)
  340. {
  341. // Get the original entity so that we can also supply the PrimaryImagePath
  342. Genre entity = Kernel.Instance.ItemController.GetGenre(key);
  343. if (entity != null)
  344. {
  345. list.Add(new CategoryInfo<Genre>()
  346. {
  347. Item = entity,
  348. ItemCount = data[key]
  349. });
  350. }
  351. }
  352. return list;
  353. }
  354. /// <summary>
  355. /// Gets all users within the system
  356. /// </summary>
  357. private IEnumerable<User> GetAllUsers()
  358. {
  359. List<User> list = new List<User>();
  360. // Return a dummy user for now since all calls to get items requre a userId
  361. User user = new User();
  362. user.Name = "Default User";
  363. user.Id = Guid.NewGuid();
  364. list.Add(user);
  365. return list;
  366. }
  367. }
  368. }