Kernel.cs 15 KB

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