Kernel.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. return item;
  108. }
  109. }
  110. return null;
  111. }
  112. private void ReloadUsers()
  113. {
  114. Users = GetAllUsers();
  115. }
  116. /// <summary>
  117. /// Reloads the root media folder
  118. /// </summary>
  119. public async Task ReloadRoot(bool allowInternetProviders = true)
  120. {
  121. if (!Directory.Exists(MediaRootFolderPath))
  122. {
  123. Directory.CreateDirectory(MediaRootFolderPath);
  124. }
  125. DirectoryWatchers.Stop();
  126. RootFolder = await ItemController.GetItem(MediaRootFolderPath, allowInternetProviders: allowInternetProviders).ConfigureAwait(false) as Folder;
  127. DirectoryWatchers.Start();
  128. }
  129. void RootFolder_ChildrenChanged(object sender, ChildrenChangedEventArgs e)
  130. {
  131. //re-start the directory watchers
  132. DirectoryWatchers.Stop();
  133. DirectoryWatchers.Start();
  134. }
  135. /// <summary>
  136. /// Gets the default user to use when EnableUserProfiles is false
  137. /// </summary>
  138. public User GetDefaultUser()
  139. {
  140. User user = Users.FirstOrDefault();
  141. return user;
  142. }
  143. /// <summary>
  144. /// Persists a User
  145. /// </summary>
  146. public void SaveUser(User user)
  147. {
  148. }
  149. /// <summary>
  150. /// Authenticates a User and returns a result indicating whether or not it succeeded
  151. /// </summary>
  152. public AuthenticationResult AuthenticateUser(User user, string password)
  153. {
  154. AuthenticationResult result = new AuthenticationResult();
  155. // When EnableUserProfiles is false, only the default User can login
  156. if (!Configuration.EnableUserProfiles)
  157. {
  158. result.Success = user.Id == GetDefaultUser().Id;
  159. }
  160. else if (string.IsNullOrEmpty(user.Password))
  161. {
  162. result.Success = true;
  163. }
  164. else
  165. {
  166. password = password ?? string.Empty;
  167. result.Success = password.GetMD5().ToString().Equals(user.Password);
  168. }
  169. // Update LastActivityDate and LastLoginDate, then save
  170. if (result.Success)
  171. {
  172. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  173. SaveUser(user);
  174. }
  175. return result;
  176. }
  177. public async Task ReloadItem(BaseItem item)
  178. {
  179. Folder folder = item as Folder;
  180. if (folder != null && folder.IsRoot)
  181. {
  182. await ReloadRoot().ConfigureAwait(false);
  183. }
  184. else
  185. {
  186. if (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  187. {
  188. await ReloadItem(item.Parent).ConfigureAwait(false);
  189. return;
  190. }
  191. BaseItem newItem = await ItemController.GetItem(item.Path, item.Parent).ConfigureAwait(false);
  192. List<BaseItem> children = item.Parent.Children.ToList();
  193. int index = children.IndexOf(item);
  194. children.RemoveAt(index);
  195. children.Insert(index, newItem);
  196. //item.Parent.ActualChildren = children.ToArray();
  197. }
  198. }
  199. /// <summary>
  200. /// Finds a library item by Id
  201. /// </summary>
  202. public BaseItem GetItemById(Guid id)
  203. {
  204. if (id == Guid.Empty)
  205. {
  206. return RootFolder;
  207. }
  208. return RootFolder.FindItemById(id);
  209. }
  210. /// <summary>
  211. /// Gets all users within the system
  212. /// </summary>
  213. private IEnumerable<User> GetAllUsers()
  214. {
  215. List<User> list = new List<User>();
  216. // Return a dummy user for now since all calls to get items requre a userId
  217. User user = new User();
  218. user.Name = "Default User";
  219. user.Id = Guid.Parse("5d1cf7fce25943b790d140095457a42b");
  220. list.Add(user);
  221. user = new User();
  222. user.Name = "Abobader";
  223. user.Id = Guid.NewGuid();
  224. user.LastLoginDate = DateTime.UtcNow.AddDays(-1);
  225. user.LastActivityDate = DateTime.UtcNow.AddHours(-3);
  226. user.Password = ("1234").GetMD5().ToString();
  227. list.Add(user);
  228. user = new User();
  229. user.Name = "Scottisafool";
  230. user.Id = Guid.NewGuid();
  231. list.Add(user);
  232. user = new User();
  233. user.Name = "Redshirt";
  234. user.Id = Guid.NewGuid();
  235. list.Add(user);
  236. /*user = new User();
  237. user.Name = "Test User 4";
  238. user.Id = Guid.NewGuid();
  239. list.Add(user);
  240. user = new User();
  241. user.Name = "Test User 5";
  242. user.Id = Guid.NewGuid();
  243. list.Add(user);
  244. user = new User();
  245. user.Name = "Test User 6";
  246. user.Id = Guid.NewGuid();
  247. list.Add(user);*/
  248. return list;
  249. }
  250. /// <summary>
  251. /// Runs all metadata providers for an entity
  252. /// </summary>
  253. internal async Task ExecuteMetadataProviders(BaseEntity item, ItemResolveEventArgs args, bool allowInternetProviders = true)
  254. {
  255. // Run them sequentially in order of priority
  256. for (int i = 0; i < MetadataProviders.Length; i++)
  257. {
  258. var provider = MetadataProviders[i];
  259. // Skip if internet providers are currently disabled
  260. if (provider.RequiresInternet && (!Configuration.EnableInternetProviders || !allowInternetProviders))
  261. {
  262. continue;
  263. }
  264. // Skip if the provider doesn't support the current item
  265. if (!provider.Supports(item))
  266. {
  267. continue;
  268. }
  269. try
  270. {
  271. await provider.FetchAsync(item, args).ConfigureAwait(false);
  272. }
  273. catch (Exception ex)
  274. {
  275. Logger.LogException(ex);
  276. }
  277. }
  278. }
  279. private void ExtractFFMpeg()
  280. {
  281. ExtractFFMpeg(ApplicationPaths.FFMpegPath);
  282. ExtractFFMpeg(ApplicationPaths.FFProbePath);
  283. }
  284. /// <summary>
  285. /// Run these during Init.
  286. /// Can't run do this on-demand because there will be multiple workers accessing them at once and we'd have to lock them
  287. /// </summary>
  288. private void ExtractFFMpeg(string exe)
  289. {
  290. if (File.Exists(exe))
  291. {
  292. File.Delete(exe);
  293. }
  294. // Extract exe
  295. using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MediaBrowser.Controller.FFMpeg." + Path.GetFileName(exe)))
  296. {
  297. using (FileStream fileStream = new FileStream(exe, FileMode.Create))
  298. {
  299. stream.CopyTo(fileStream);
  300. }
  301. }
  302. }
  303. }
  304. }