Kernel.cs 12 KB

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