Kernel.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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.Common.Serialization;
  12. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.Events;
  14. using MediaBrowser.Controller.IO;
  15. using MediaBrowser.Controller.Library;
  16. using MediaBrowser.Controller.Resolvers;
  17. using MediaBrowser.Model.Configuration;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.Users;
  20. namespace MediaBrowser.Controller
  21. {
  22. public class Kernel : BaseKernel<ServerConfiguration>
  23. {
  24. public static Kernel Instance { get; private set; }
  25. public ItemController ItemController { get; private set; }
  26. public IEnumerable<User> Users { get; private set; }
  27. public Folder RootFolder { get; private set; }
  28. private DirectoryWatchers DirectoryWatchers { get; set; }
  29. private string MediaRootFolderPath
  30. {
  31. get
  32. {
  33. return ApplicationPaths.RootFolderPath;
  34. }
  35. }
  36. //gonna want to load this from the standard repository... -ebr
  37. //private string UsersPath
  38. //{
  39. // get
  40. // {
  41. // return Path.Combine(ProgramDataPath, "Users");
  42. // }
  43. //}
  44. /// <summary>
  45. /// Gets the list of currently registered entity resolvers
  46. /// </summary>
  47. [ImportMany(typeof(IBaseItemResolver))]
  48. public IEnumerable<IBaseItemResolver> EntityResolvers { get; private set; }
  49. /// <summary>
  50. /// Creates a kernal based on a Data path, which is akin to our current programdata path
  51. /// </summary>
  52. public Kernel()
  53. : base()
  54. {
  55. Instance = this;
  56. ItemController = new ItemController();
  57. DirectoryWatchers = new DirectoryWatchers();
  58. ItemController.PreBeginResolvePath += ItemController_PreBeginResolvePath;
  59. ItemController.BeginResolvePath += ItemController_BeginResolvePath;
  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. // Get users from users folder
  72. // Load root media folder
  73. Parallel.Invoke(ReloadUsers, ReloadRoot);
  74. }
  75. /// <summary>
  76. /// Fires when a path is about to be resolved, but before child folders and files
  77. /// have been collected from the file system.
  78. /// This gives us a chance to cancel it if needed, resulting in the path being ignored
  79. /// </summary>
  80. void ItemController_PreBeginResolvePath(object sender, PreBeginResolveEventArgs e)
  81. {
  82. if (e.IsHidden || e.IsSystemFile)
  83. {
  84. // Ignore hidden files and folders
  85. e.Cancel = true;
  86. }
  87. else if (Path.GetFileName(e.Path).Equals("trailers", StringComparison.OrdinalIgnoreCase))
  88. {
  89. // Ignore any folders named "trailers"
  90. e.Cancel = true;
  91. }
  92. }
  93. /// <summary>
  94. /// Fires when a path is about to be resolved, but after child folders and files
  95. /// This gives us a chance to cancel it if needed, resulting in the path being ignored
  96. /// </summary>
  97. void ItemController_BeginResolvePath(object sender, ItemResolveEventArgs e)
  98. {
  99. if (e.IsFolder)
  100. {
  101. if (e.ContainsFile(".ignore"))
  102. {
  103. // Ignore any folders containing a file called .ignore
  104. e.Cancel = true;
  105. }
  106. }
  107. }
  108. private void ReloadUsers()
  109. {
  110. Users = GetAllUsers();
  111. }
  112. /// <summary>
  113. /// Reloads the root media folder
  114. /// </summary>
  115. public void ReloadRoot()
  116. {
  117. if (!Directory.Exists(MediaRootFolderPath))
  118. {
  119. Directory.CreateDirectory(MediaRootFolderPath);
  120. }
  121. DirectoryWatchers.Stop();
  122. RootFolder = ItemController.GetItem(MediaRootFolderPath) as Folder;
  123. DirectoryWatchers.Start();
  124. }
  125. private static MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
  126. public static Guid GetMD5(string str)
  127. {
  128. lock (md5Provider)
  129. {
  130. return new Guid(md5Provider.ComputeHash(Encoding.Unicode.GetBytes(str)));
  131. }
  132. }
  133. public UserConfiguration GetUserConfiguration(Guid userId)
  134. {
  135. return Configuration.DefaultUserConfiguration;
  136. }
  137. public void ReloadItem(BaseItem item)
  138. {
  139. Folder folder = item as Folder;
  140. if (folder != null && folder.IsRoot)
  141. {
  142. ReloadRoot();
  143. }
  144. else
  145. {
  146. if (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  147. {
  148. ReloadItem(item.Parent);
  149. return;
  150. }
  151. BaseItem newItem = ItemController.GetItem(item.Parent, item.Path);
  152. List<BaseItem> children = item.Parent.Children.ToList();
  153. int index = children.IndexOf(item);
  154. children.RemoveAt(index);
  155. children.Insert(index, newItem);
  156. item.Parent.Children = children.ToArray();
  157. }
  158. }
  159. /// <summary>
  160. /// Finds a library item by Id
  161. /// </summary>
  162. public BaseItem GetItemById(Guid id)
  163. {
  164. if (id == Guid.Empty)
  165. {
  166. return RootFolder;
  167. }
  168. return RootFolder.FindById(id);
  169. }
  170. /// <summary>
  171. /// Determines if an item is allowed for a given user
  172. /// </summary>
  173. public bool IsParentalAllowed(BaseItem item, Guid userId)
  174. {
  175. // not yet implemented
  176. return true;
  177. }
  178. /// <summary>
  179. /// Gets allowed children of an item
  180. /// </summary>
  181. public IEnumerable<BaseItem> GetParentalAllowedChildren(Folder folder, Guid userId)
  182. {
  183. return folder.Children.Where(i => IsParentalAllowed(i, userId));
  184. }
  185. /// <summary>
  186. /// Gets allowed recursive children of an item
  187. /// </summary>
  188. public IEnumerable<BaseItem> GetParentalAllowedRecursiveChildren(Folder folder, Guid userId)
  189. {
  190. foreach (var item in GetParentalAllowedChildren(folder, userId))
  191. {
  192. yield return item;
  193. var subFolder = item as Folder;
  194. if (subFolder != null)
  195. {
  196. foreach (var subitem in GetParentalAllowedRecursiveChildren(subFolder, userId))
  197. {
  198. yield return subitem;
  199. }
  200. }
  201. }
  202. }
  203. /// <summary>
  204. /// Gets user data for an item, if there is any
  205. /// </summary>
  206. public UserItemData GetUserItemData(Guid userId, Guid itemId)
  207. {
  208. User user = Users.First(u => u.Id == userId);
  209. if (user.ItemData.ContainsKey(itemId))
  210. {
  211. return user.ItemData[itemId];
  212. }
  213. return null;
  214. }
  215. /// <summary>
  216. /// Gets all recently added items (recursive) within a folder, based on configuration and parental settings
  217. /// </summary>
  218. public IEnumerable<BaseItem> GetRecentlyAddedItems(Folder parent, Guid userId)
  219. {
  220. DateTime now = DateTime.Now;
  221. UserConfiguration config = GetUserConfiguration(userId);
  222. return GetParentalAllowedRecursiveChildren(parent, userId).Where(i => !(i is Folder) && (now - i.DateCreated).TotalDays < config.RecentItemDays);
  223. }
  224. /// <summary>
  225. /// Gets all recently added unplayed items (recursive) within a folder, based on configuration and parental settings
  226. /// </summary>
  227. public IEnumerable<BaseItem> GetRecentlyAddedUnplayedItems(Folder parent, Guid userId)
  228. {
  229. return GetRecentlyAddedItems(parent, userId).Where(i =>
  230. {
  231. var userdata = GetUserItemData(userId, i.Id);
  232. return userdata == null || userdata.PlayCount == 0;
  233. });
  234. }
  235. /// <summary>
  236. /// Gets all in-progress items (recursive) within a folder
  237. /// </summary>
  238. public IEnumerable<BaseItem> GetInProgressItems(Folder parent, Guid userId)
  239. {
  240. return GetParentalAllowedRecursiveChildren(parent, userId).Where(i =>
  241. {
  242. if (i is Folder)
  243. {
  244. return false;
  245. }
  246. var userdata = GetUserItemData(userId, i.Id);
  247. return userdata != null && userdata.PlaybackPosition.Ticks > 0;
  248. });
  249. }
  250. /// <summary>
  251. /// Finds all recursive items within a top-level parent that contain the given studio and are allowed for the current user
  252. /// </summary>
  253. public IEnumerable<BaseItem> GetItemsWithStudio(Folder parent, string studio, Guid userId)
  254. {
  255. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.Studios != null && f.Studios.Any(s => s.Equals(studio, StringComparison.OrdinalIgnoreCase)));
  256. }
  257. /// <summary>
  258. /// Finds all recursive items within a top-level parent that contain the given genre and are allowed for the current user
  259. /// </summary>
  260. public IEnumerable<BaseItem> GetItemsWithGenre(Folder parent, string genre, Guid userId)
  261. {
  262. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.Genres != null && f.Genres.Any(s => s.Equals(genre, StringComparison.OrdinalIgnoreCase)));
  263. }
  264. /// <summary>
  265. /// Finds all recursive items within a top-level parent that contain the given person and are allowed for the current user
  266. /// </summary>
  267. public IEnumerable<BaseItem> GetItemsWithPerson(Folder parent, string personName, Guid userId)
  268. {
  269. return GetParentalAllowedRecursiveChildren(parent, userId).Where(f => f.People != null && f.People.Any(s => s.Name.Equals(personName, StringComparison.OrdinalIgnoreCase)));
  270. }
  271. /// <summary>
  272. /// Gets all studios from all recursive children of a folder
  273. /// The CategoryInfo class is used to keep track of the number of times each studio appears
  274. /// </summary>
  275. public IEnumerable<CategoryInfo<Studio>> GetAllStudios(Folder parent, Guid userId)
  276. {
  277. Dictionary<string, int> data = new Dictionary<string, int>();
  278. // Get all the allowed recursive children
  279. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  280. foreach (var item in allItems)
  281. {
  282. // Add each studio from the item to the data dictionary
  283. // If the studio already exists, increment the count
  284. if (item.Studios == null)
  285. {
  286. continue;
  287. }
  288. foreach (string val in item.Studios)
  289. {
  290. if (!data.ContainsKey(val))
  291. {
  292. data.Add(val, 1);
  293. }
  294. else
  295. {
  296. data[val]++;
  297. }
  298. }
  299. }
  300. // Now go through the dictionary and create a Category for each studio
  301. List<CategoryInfo<Studio>> list = new List<CategoryInfo<Studio>>();
  302. foreach (string key in data.Keys)
  303. {
  304. // Get the original entity so that we can also supply the PrimaryImagePath
  305. Studio entity = Kernel.Instance.ItemController.GetStudio(key);
  306. if (entity != null)
  307. {
  308. list.Add(new CategoryInfo<Studio>()
  309. {
  310. Item = entity,
  311. ItemCount = data[key]
  312. });
  313. }
  314. }
  315. return list;
  316. }
  317. /// <summary>
  318. /// Gets all genres from all recursive children of a folder
  319. /// The CategoryInfo class is used to keep track of the number of times each genres appears
  320. /// </summary>
  321. public IEnumerable<CategoryInfo<Genre>> GetAllGenres(Folder parent, Guid userId)
  322. {
  323. Dictionary<string, int> data = new Dictionary<string, int>();
  324. // Get all the allowed recursive children
  325. IEnumerable<BaseItem> allItems = Kernel.Instance.GetParentalAllowedRecursiveChildren(parent, userId);
  326. foreach (var item in allItems)
  327. {
  328. // Add each genre from the item to the data dictionary
  329. // If the genre already exists, increment the count
  330. if (item.Genres == null)
  331. {
  332. continue;
  333. }
  334. foreach (string val in item.Genres)
  335. {
  336. if (!data.ContainsKey(val))
  337. {
  338. data.Add(val, 1);
  339. }
  340. else
  341. {
  342. data[val]++;
  343. }
  344. }
  345. }
  346. // Now go through the dictionary and create a Category for each genre
  347. List<CategoryInfo<Genre>> list = new List<CategoryInfo<Genre>>();
  348. foreach (string key in data.Keys)
  349. {
  350. // Get the original entity so that we can also supply the PrimaryImagePath
  351. Genre entity = Kernel.Instance.ItemController.GetGenre(key);
  352. if (entity != null)
  353. {
  354. list.Add(new CategoryInfo<Genre>()
  355. {
  356. Item = entity,
  357. ItemCount = data[key]
  358. });
  359. }
  360. }
  361. return list;
  362. }
  363. /// <summary>
  364. /// Gets all users within the system
  365. /// </summary>
  366. private IEnumerable<User> GetAllUsers()
  367. {
  368. //we'll get this from the standard repo... -ebr
  369. //if (!Directory.Exists(UsersPath))
  370. //{
  371. // Directory.CreateDirectory(UsersPath);
  372. //}
  373. List<User> list = new List<User>();
  374. //foreach (string folder in Directory.GetDirectories(UsersPath, "*", SearchOption.TopDirectoryOnly))
  375. //{
  376. // User item = GetFromDirectory(folder);
  377. // if (item != null)
  378. // {
  379. // list.Add(item);
  380. // }
  381. //}
  382. return list;
  383. }
  384. /// <summary>
  385. /// Gets a User from it's directory
  386. /// </summary>
  387. //private User GetFromDirectory(string path)
  388. //{
  389. // string file = Path.Combine(path, "user.js");
  390. // return JsonSerializer.DeserializeFromFile<User>(file);
  391. //}
  392. /// <summary>
  393. /// Creates a User with a given name
  394. /// </summary>
  395. //public User CreateUser(string name)
  396. //{
  397. // var now = DateTime.Now;
  398. // User user = new User()
  399. // {
  400. // Name = name,
  401. // Id = Guid.NewGuid(),
  402. // DateCreated = now,
  403. // DateModified = now
  404. // };
  405. // user.Path = Path.Combine(UsersPath, user.Id.ToString());
  406. // Directory.CreateDirectory(user.Path);
  407. // JsonSerializer.SerializeToFile(user, Path.Combine(user.Path, "user.js"));
  408. // return user;
  409. //}
  410. }
  411. }