Kernel.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. //Task.Delay(30000); //let's wait and see if more data gets filled in...
  165. var allChildren = RootFolder.RecursiveChildren;
  166. Logger.LogDebugInfo(string.Format("Loading complete. Movies: {0} Episodes: {1} Folders: {2}", allChildren.OfType<Entities.Movies.Movie>().Count(), allChildren.OfType<Entities.TV.Episode>().Count(), allChildren.Where(i => i is Folder && !(i is Series || i is Season)).Count()));
  167. foreach (var child in allChildren)
  168. {
  169. Logger.LogDebugInfo("(" + child.GetType().Name + ") " + child.Name + " (" + child.Path + ")");
  170. }
  171. }
  172. /// <summary>
  173. /// Gets the default user to use when EnableUserProfiles is false
  174. /// </summary>
  175. public User GetDefaultUser()
  176. {
  177. User user = Users.FirstOrDefault();
  178. return user;
  179. }
  180. /// <summary>
  181. /// Persists a User
  182. /// </summary>
  183. public void SaveUser(User user)
  184. {
  185. }
  186. /// <summary>
  187. /// Authenticates a User and returns a result indicating whether or not it succeeded
  188. /// </summary>
  189. public AuthenticationResult AuthenticateUser(User user, string password)
  190. {
  191. var result = new AuthenticationResult();
  192. // When EnableUserProfiles is false, only the default User can login
  193. if (!Configuration.EnableUserProfiles)
  194. {
  195. result.Success = user.Id == GetDefaultUser().Id;
  196. }
  197. else if (string.IsNullOrEmpty(user.Password))
  198. {
  199. result.Success = true;
  200. }
  201. else
  202. {
  203. password = password ?? string.Empty;
  204. result.Success = password.GetMD5().ToString().Equals(user.Password);
  205. }
  206. // Update LastActivityDate and LastLoginDate, then save
  207. if (result.Success)
  208. {
  209. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  210. SaveUser(user);
  211. }
  212. return result;
  213. }
  214. public async Task ReloadItem(BaseItem item)
  215. {
  216. var folder = item as Folder;
  217. if (folder != null && folder.IsRoot)
  218. {
  219. await ReloadRoot().ConfigureAwait(false);
  220. }
  221. else
  222. {
  223. if (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  224. {
  225. await ReloadItem(item.Parent).ConfigureAwait(false);
  226. return;
  227. }
  228. BaseItem newItem = await ItemController.GetItem(item.Path, item.Parent).ConfigureAwait(false);
  229. List<BaseItem> children = item.Parent.Children.ToList();
  230. int index = children.IndexOf(item);
  231. children.RemoveAt(index);
  232. children.Insert(index, newItem);
  233. //item.Parent.ActualChildren = children.ToArray();
  234. }
  235. }
  236. /// <summary>
  237. /// Finds a library item by Id
  238. /// </summary>
  239. public BaseItem GetItemById(Guid id)
  240. {
  241. if (id == Guid.Empty)
  242. {
  243. return RootFolder;
  244. }
  245. return RootFolder.FindItemById(id);
  246. }
  247. /// <summary>
  248. /// Gets all users within the system
  249. /// </summary>
  250. private IEnumerable<User> GetAllUsers()
  251. {
  252. var list = new List<User>();
  253. // Return a dummy user for now since all calls to get items requre a userId
  254. var user = new User { };
  255. user.Name = "Default User";
  256. user.Id = Guid.Parse("5d1cf7fce25943b790d140095457a42b");
  257. user.PrimaryImagePath = "D:\\Video\\TV\\Archer (2009)\\backdrop.jpg";
  258. list.Add(user);
  259. user = new User { };
  260. user.Name = "Abobader";
  261. user.Id = Guid.NewGuid();
  262. user.LastLoginDate = DateTime.UtcNow.AddDays(-1);
  263. user.LastActivityDate = DateTime.UtcNow.AddHours(-3);
  264. user.Password = ("1234").GetMD5().ToString();
  265. list.Add(user);
  266. user = new User { };
  267. user.Name = "Scottisafool";
  268. user.Id = Guid.NewGuid();
  269. list.Add(user);
  270. user = new User { };
  271. user.Name = "Redshirt";
  272. user.Id = Guid.NewGuid();
  273. list.Add(user);
  274. /*user = new User();
  275. user.Name = "Test User 4";
  276. user.Id = Guid.NewGuid();
  277. list.Add(user);
  278. user = new User();
  279. user.Name = "Test User 5";
  280. user.Id = Guid.NewGuid();
  281. list.Add(user);
  282. user = new User();
  283. user.Name = "Test User 6";
  284. user.Id = Guid.NewGuid();
  285. list.Add(user);*/
  286. return list;
  287. }
  288. /// <summary>
  289. /// Runs all metadata providers for an entity
  290. /// </summary>
  291. internal async Task ExecuteMetadataProviders(BaseEntity item, bool allowInternetProviders = true)
  292. {
  293. // Run them sequentially in order of priority
  294. for (int i = 0; i < MetadataProviders.Length; i++)
  295. {
  296. var provider = MetadataProviders[i];
  297. // Skip if internet providers are currently disabled
  298. if (provider.RequiresInternet && (!Configuration.EnableInternetProviders || !allowInternetProviders))
  299. {
  300. continue;
  301. }
  302. // Skip if the provider doesn't support the current item
  303. if (!provider.Supports(item))
  304. {
  305. continue;
  306. }
  307. try
  308. {
  309. await provider.FetchIfNeededAsync(item).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. }