Kernel.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. using MediaBrowser.Common.Kernel;
  2. using MediaBrowser.Common.Logging;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.TV;
  5. using MediaBrowser.Controller.IO;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Controller.Resolvers;
  9. using MediaBrowser.Controller.Weather;
  10. using MediaBrowser.Model.Authentication;
  11. using MediaBrowser.Model.Configuration;
  12. using MediaBrowser.Model.Progress;
  13. using MediaBrowser.Common.Extensions;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.ComponentModel.Composition;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Reflection;
  20. using System.Security.Cryptography;
  21. using System.Text;
  22. using System.Threading.Tasks;
  23. namespace MediaBrowser.Controller
  24. {
  25. public class Kernel : BaseKernel<ServerConfiguration, ServerApplicationPaths>
  26. {
  27. #region Events
  28. /// <summary>
  29. /// Fires whenever any validation routine adds or removes items. The added and removed items are properties of the args.
  30. /// *** Will fire asynchronously. ***
  31. /// </summary>
  32. public event EventHandler<ChildrenChangedEventArgs> LibraryChanged;
  33. public void OnLibraryChanged(ChildrenChangedEventArgs args)
  34. {
  35. if (LibraryChanged != null)
  36. {
  37. Task.Run(() => LibraryChanged(this, args));
  38. }
  39. }
  40. #endregion
  41. public static Kernel Instance { get; private set; }
  42. public ItemController ItemController { get; private set; }
  43. public WeatherClient WeatherClient { get; private set; }
  44. public IEnumerable<User> Users { get; private set; }
  45. public Folder RootFolder { get; private set; }
  46. private DirectoryWatchers DirectoryWatchers { get; set; }
  47. private string MediaRootFolderPath
  48. {
  49. get
  50. {
  51. return ApplicationPaths.RootFolderPath;
  52. }
  53. }
  54. public override KernelContext KernelContext
  55. {
  56. get { return KernelContext.Server; }
  57. }
  58. /// <summary>
  59. /// Gets the list of currently registered metadata prvoiders
  60. /// </summary>
  61. [ImportMany(typeof(BaseMetadataProvider))]
  62. private IEnumerable<BaseMetadataProvider> MetadataProvidersEnumerable { get; set; }
  63. /// <summary>
  64. /// Once MEF has loaded the resolvers, sort them by priority and store them in this array
  65. /// Given the sheer number of times they'll be iterated over it'll be faster to loop through an array
  66. /// </summary>
  67. private BaseMetadataProvider[] MetadataProviders { get; set; }
  68. /// <summary>
  69. /// Gets the list of currently registered entity resolvers
  70. /// </summary>
  71. [ImportMany(typeof(IBaseItemResolver))]
  72. private IEnumerable<IBaseItemResolver> EntityResolversEnumerable { get; set; }
  73. /// <summary>
  74. /// Once MEF has loaded the resolvers, sort them by priority and store them in this array
  75. /// Given the sheer number of times they'll be iterated over it'll be faster to loop through an array
  76. /// </summary>
  77. internal IBaseItemResolver[] EntityResolvers { get; private set; }
  78. /// <summary>
  79. /// Creates a kernel based on a Data path, which is akin to our current programdata path
  80. /// </summary>
  81. public Kernel()
  82. : base()
  83. {
  84. Instance = this;
  85. }
  86. /// <summary>
  87. /// Performs initializations that only occur once
  88. /// </summary>
  89. protected override void InitializeInternal(IProgress<TaskProgress> progress)
  90. {
  91. ItemController = new ItemController();
  92. DirectoryWatchers = new DirectoryWatchers();
  93. base.InitializeInternal(progress);
  94. }
  95. /// <summary>
  96. /// Performs initializations that can be reloaded at anytime
  97. /// </summary>
  98. public override async Task Reload(IProgress<TaskProgress> progress)
  99. {
  100. await base.Reload(progress).ConfigureAwait(false);
  101. ReloadWeatherClient();
  102. ExtractFFMpeg();
  103. progress.Report(new TaskProgress { Description = "Loading Users" });
  104. ReloadUsers();
  105. progress.Report(new TaskProgress { Description = "Loading Media Library" });
  106. await ReloadRoot(allowInternetProviders: false).ConfigureAwait(false);
  107. }
  108. /// <summary>
  109. /// Completely disposes the Kernel
  110. /// </summary>
  111. public override void Dispose()
  112. {
  113. base.Dispose();
  114. DirectoryWatchers.Stop();
  115. DisposeWeatherClient();
  116. }
  117. protected override void OnComposablePartsLoaded()
  118. {
  119. // The base class will start up all the plugins
  120. base.OnComposablePartsLoaded();
  121. // Sort the resolvers by priority
  122. EntityResolvers = EntityResolversEnumerable.OrderBy(e => e.Priority).ToArray();
  123. // Sort the providers by priority
  124. MetadataProviders = MetadataProvidersEnumerable.OrderBy(e => e.Priority).ToArray();
  125. }
  126. public BaseItem ResolveItem(ItemResolveEventArgs args)
  127. {
  128. // Try first priority resolvers
  129. for (int i = 0; i < EntityResolvers.Length; i++)
  130. {
  131. var item = EntityResolvers[i].ResolvePath(args);
  132. if (item != null)
  133. {
  134. item.ResolveArgs = args;
  135. return item;
  136. }
  137. }
  138. return null;
  139. }
  140. private void ReloadUsers()
  141. {
  142. Users = GetAllUsers();
  143. }
  144. /// <summary>
  145. /// Reloads the root media folder
  146. /// </summary>
  147. public async Task ReloadRoot(bool allowInternetProviders = true)
  148. {
  149. if (!Directory.Exists(MediaRootFolderPath))
  150. {
  151. Directory.CreateDirectory(MediaRootFolderPath);
  152. }
  153. DirectoryWatchers.Stop();
  154. RootFolder = await ItemController.GetItem(MediaRootFolderPath, allowInternetProviders: allowInternetProviders).ConfigureAwait(false) as Folder;
  155. RootFolder.ChildrenChanged += RootFolder_ChildrenChanged;
  156. DirectoryWatchers.Start();
  157. }
  158. void RootFolder_ChildrenChanged(object sender, ChildrenChangedEventArgs e)
  159. {
  160. Logger.LogDebugInfo("Root Folder Children Changed. Added: " + e.ItemsAdded.Count + " Removed: " + e.ItemsRemoved.Count());
  161. //re-start the directory watchers
  162. DirectoryWatchers.Stop();
  163. DirectoryWatchers.Start();
  164. var allChildren = RootFolder.RecursiveChildren;
  165. Logger.LogInfo(string.Format("Loading complete. Movies: {0} Episodes: {1}", allChildren.OfType<Entities.Movies.Movie>().Count(), allChildren.OfType<Entities.TV.Episode>().Count()));
  166. }
  167. /// <summary>
  168. /// Gets the default user to use when EnableUserProfiles is false
  169. /// </summary>
  170. public User GetDefaultUser()
  171. {
  172. User user = Users.FirstOrDefault();
  173. return user;
  174. }
  175. /// <summary>
  176. /// Persists a User
  177. /// </summary>
  178. public void SaveUser(User user)
  179. {
  180. }
  181. /// <summary>
  182. /// Authenticates a User and returns a result indicating whether or not it succeeded
  183. /// </summary>
  184. public AuthenticationResult AuthenticateUser(User user, string password)
  185. {
  186. var result = new AuthenticationResult();
  187. // When EnableUserProfiles is false, only the default User can login
  188. if (!Configuration.EnableUserProfiles)
  189. {
  190. result.Success = user.Id == GetDefaultUser().Id;
  191. }
  192. else if (string.IsNullOrEmpty(user.Password))
  193. {
  194. result.Success = true;
  195. }
  196. else
  197. {
  198. password = password ?? string.Empty;
  199. result.Success = password.GetMD5().ToString().Equals(user.Password);
  200. }
  201. // Update LastActivityDate and LastLoginDate, then save
  202. if (result.Success)
  203. {
  204. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  205. SaveUser(user);
  206. }
  207. return result;
  208. }
  209. public async Task ReloadItem(BaseItem item)
  210. {
  211. var folder = item as Folder;
  212. if (folder != null && folder.IsRoot)
  213. {
  214. await ReloadRoot().ConfigureAwait(false);
  215. }
  216. else
  217. {
  218. if (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  219. {
  220. await ReloadItem(item.Parent).ConfigureAwait(false);
  221. return;
  222. }
  223. BaseItem newItem = await ItemController.GetItem(item.Path, item.Parent).ConfigureAwait(false);
  224. List<BaseItem> children = item.Parent.Children.ToList();
  225. int index = children.IndexOf(item);
  226. children.RemoveAt(index);
  227. children.Insert(index, newItem);
  228. //item.Parent.ActualChildren = children.ToArray();
  229. }
  230. }
  231. /// <summary>
  232. /// Finds a library item by Id
  233. /// </summary>
  234. public BaseItem GetItemById(Guid id)
  235. {
  236. if (id == Guid.Empty)
  237. {
  238. return RootFolder;
  239. }
  240. return RootFolder.FindItemById(id);
  241. }
  242. /// <summary>
  243. /// Gets all users within the system
  244. /// </summary>
  245. private IEnumerable<User> GetAllUsers()
  246. {
  247. var list = new List<User>();
  248. // Return a dummy user for now since all calls to get items requre a userId
  249. var user = new User { };
  250. user.Name = "Default User";
  251. user.Id = Guid.Parse("5d1cf7fce25943b790d140095457a42b");
  252. user.PrimaryImagePath = "D:\\Video\\TV\\Archer (2009)\\backdrop.jpg";
  253. list.Add(user);
  254. user = new User { };
  255. user.Name = "Abobader";
  256. user.Id = Guid.NewGuid();
  257. user.LastLoginDate = DateTime.UtcNow.AddDays(-1);
  258. user.LastActivityDate = DateTime.UtcNow.AddHours(-3);
  259. user.Password = ("1234").GetMD5().ToString();
  260. list.Add(user);
  261. user = new User { };
  262. user.Name = "Scottisafool";
  263. user.Id = Guid.NewGuid();
  264. list.Add(user);
  265. user = new User { };
  266. user.Name = "Redshirt";
  267. user.Id = Guid.NewGuid();
  268. list.Add(user);
  269. /*user = new User();
  270. user.Name = "Test User 4";
  271. user.Id = Guid.NewGuid();
  272. list.Add(user);
  273. user = new User();
  274. user.Name = "Test User 5";
  275. user.Id = Guid.NewGuid();
  276. list.Add(user);
  277. user = new User();
  278. user.Name = "Test User 6";
  279. user.Id = Guid.NewGuid();
  280. list.Add(user);*/
  281. return list;
  282. }
  283. /// <summary>
  284. /// Runs all metadata providers for an entity
  285. /// </summary>
  286. internal async Task ExecuteMetadataProviders(BaseEntity item, bool allowInternetProviders = true)
  287. {
  288. // Run them sequentially in order of priority
  289. for (int i = 0; i < MetadataProviders.Length; i++)
  290. {
  291. var provider = MetadataProviders[i];
  292. // Skip if internet providers are currently disabled
  293. if (provider.RequiresInternet && (!Configuration.EnableInternetProviders || !allowInternetProviders))
  294. {
  295. continue;
  296. }
  297. // Skip if the provider doesn't support the current item
  298. if (!provider.Supports(item))
  299. {
  300. continue;
  301. }
  302. // Skip if provider says we don't need to run
  303. if (!provider.NeedsRefresh(item))
  304. {
  305. continue;
  306. }
  307. try
  308. {
  309. await provider.FetchAsync(item, item.ResolveArgs).ConfigureAwait(false);
  310. }
  311. catch (Exception ex)
  312. {
  313. Logger.LogException(ex);
  314. }
  315. }
  316. }
  317. private void ExtractFFMpeg()
  318. {
  319. ExtractFFMpeg(ApplicationPaths.FFMpegPath);
  320. ExtractFFMpeg(ApplicationPaths.FFProbePath);
  321. }
  322. /// <summary>
  323. /// Run these during Init.
  324. /// Can't run do this on-demand because there will be multiple workers accessing them at once and we'd have to lock them
  325. /// </summary>
  326. private void ExtractFFMpeg(string exe)
  327. {
  328. if (File.Exists(exe))
  329. {
  330. File.Delete(exe);
  331. }
  332. // Extract exe
  333. using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MediaBrowser.Controller.FFMpeg." + Path.GetFileName(exe)))
  334. {
  335. using (var fileStream = new FileStream(exe, FileMode.Create))
  336. {
  337. stream.CopyTo(fileStream);
  338. }
  339. }
  340. }
  341. /// <summary>
  342. /// Disposes the current WeatherClient
  343. /// </summary>
  344. private void DisposeWeatherClient()
  345. {
  346. if (WeatherClient != null)
  347. {
  348. WeatherClient.Dispose();
  349. }
  350. }
  351. /// <summary>
  352. /// Disposes the current WeatherClient and creates a new one
  353. /// </summary>
  354. private void ReloadWeatherClient()
  355. {
  356. DisposeWeatherClient();
  357. WeatherClient = new WeatherClient();
  358. }
  359. }
  360. }