Kernel.cs 16 KB

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