Kernel.cs 13 KB

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