Kernel.cs 16 KB

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