Kernel.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. using MediaBrowser.Common.Kernel;
  2. using MediaBrowser.Common.Logging;
  3. using MediaBrowser.Controller.IO;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Providers;
  6. using MediaBrowser.Controller.Resolvers;
  7. using MediaBrowser.Controller.Weather;
  8. using MediaBrowser.Model.Authentication;
  9. using MediaBrowser.Model.Configuration;
  10. using MediaBrowser.Model.Entities;
  11. using MediaBrowser.Model.Progress;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.ComponentModel.Composition;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Reflection;
  18. using System.Security.Cryptography;
  19. using System.Text;
  20. using System.Threading.Tasks;
  21. namespace MediaBrowser.Controller
  22. {
  23. public class Kernel : BaseKernel<ServerConfiguration, ServerApplicationPaths>
  24. {
  25. public static Kernel Instance { get; private set; }
  26. public ItemController ItemController { get; private set; }
  27. public WeatherClient WeatherClient { get; private set; }
  28. public IEnumerable<User> Users { get; private set; }
  29. public Folder RootFolder { get; private set; }
  30. private DirectoryWatchers DirectoryWatchers { get; set; }
  31. private string MediaRootFolderPath
  32. {
  33. get
  34. {
  35. return ApplicationPaths.RootFolderPath;
  36. }
  37. }
  38. public override KernelContext KernelContext
  39. {
  40. get { return KernelContext.Server; }
  41. }
  42. /// <summary>
  43. /// Gets the list of currently registered metadata prvoiders
  44. /// </summary>
  45. [ImportMany(typeof(BaseMetadataProvider))]
  46. private IEnumerable<BaseMetadataProvider> MetadataProvidersEnumerable { get; set; }
  47. /// <summary>
  48. /// Once MEF has loaded the resolvers, sort them by priority and store them in this array
  49. /// Given the sheer number of times they'll be iterated over it'll be faster to loop through an array
  50. /// </summary>
  51. private BaseMetadataProvider[] MetadataProviders { get; set; }
  52. /// <summary>
  53. /// Gets the list of currently registered entity resolvers
  54. /// </summary>
  55. [ImportMany(typeof(IBaseItemResolver))]
  56. private IEnumerable<IBaseItemResolver> EntityResolversEnumerable { get; set; }
  57. /// <summary>
  58. /// Once MEF has loaded the resolvers, sort them by priority and store them in this array
  59. /// Given the sheer number of times they'll be iterated over it'll be faster to loop through an array
  60. /// </summary>
  61. internal IBaseItemResolver[] EntityResolvers { get; private set; }
  62. /// <summary>
  63. /// Creates a kernel based on a Data path, which is akin to our current programdata path
  64. /// </summary>
  65. public Kernel()
  66. : base()
  67. {
  68. Instance = this;
  69. ItemController = new ItemController();
  70. DirectoryWatchers = new DirectoryWatchers();
  71. WeatherClient = new WeatherClient();
  72. ItemController.PreBeginResolvePath += ItemController_PreBeginResolvePath;
  73. ItemController.BeginResolvePath += ItemController_BeginResolvePath;
  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. }
  85. protected override void OnComposablePartsLoaded()
  86. {
  87. // The base class will start up all the plugins
  88. base.OnComposablePartsLoaded();
  89. // Sort the resolvers by priority
  90. EntityResolvers = EntityResolversEnumerable.OrderBy(e => e.Priority).ToArray();
  91. // Sort the providers by priority
  92. MetadataProviders = MetadataProvidersEnumerable.OrderBy(e => e.Priority).ToArray();
  93. // Initialize the metadata providers
  94. Parallel.ForEach(MetadataProviders, provider =>
  95. {
  96. provider.Init();
  97. });
  98. }
  99. /// <summary>
  100. /// Fires when a path is about to be resolved, but before child folders and files
  101. /// have been collected from the file system.
  102. /// This gives us a chance to cancel it if needed, resulting in the path being ignored
  103. /// </summary>
  104. void ItemController_PreBeginResolvePath(object sender, PreBeginResolveEventArgs e)
  105. {
  106. if (e.IsHidden || e.IsSystemFile)
  107. {
  108. // Ignore hidden files and folders
  109. e.Cancel = true;
  110. }
  111. else if (Path.GetFileName(e.Path).Equals("trailers", StringComparison.OrdinalIgnoreCase))
  112. {
  113. // Ignore any folders named "trailers"
  114. e.Cancel = true;
  115. }
  116. }
  117. /// <summary>
  118. /// Fires when a path is about to be resolved, but after child folders and files
  119. /// This gives us a chance to cancel it if needed, resulting in the path being ignored
  120. /// </summary>
  121. void ItemController_BeginResolvePath(object sender, ItemResolveEventArgs e)
  122. {
  123. if (e.ContainsFile(".ignore"))
  124. {
  125. // Ignore any folders containing a file called .ignore
  126. e.Cancel = true;
  127. }
  128. }
  129. private void ReloadUsers()
  130. {
  131. Users = GetAllUsers();
  132. }
  133. /// <summary>
  134. /// Reloads the root media folder
  135. /// </summary>
  136. public async Task ReloadRoot(bool allowInternetProviders = true)
  137. {
  138. if (!Directory.Exists(MediaRootFolderPath))
  139. {
  140. Directory.CreateDirectory(MediaRootFolderPath);
  141. }
  142. DirectoryWatchers.Stop();
  143. RootFolder = await ItemController.GetItem(MediaRootFolderPath, allowInternetProviders: allowInternetProviders).ConfigureAwait(false) as Folder;
  144. DirectoryWatchers.Start();
  145. }
  146. public static Guid GetMD5(string str)
  147. {
  148. using (var provider = new MD5CryptoServiceProvider())
  149. {
  150. return new Guid(provider.ComputeHash(Encoding.Unicode.GetBytes(str)));
  151. }
  152. }
  153. /// <summary>
  154. /// Gets the default user to use when EnableUserProfiles is false
  155. /// </summary>
  156. public User GetDefaultUser()
  157. {
  158. User user = Users.FirstOrDefault();
  159. return user;
  160. }
  161. /// <summary>
  162. /// Persists a User
  163. /// </summary>
  164. public void SaveUser(User user)
  165. {
  166. }
  167. /// <summary>
  168. /// Authenticates a User and returns a result indicating whether or not it succeeded
  169. /// </summary>
  170. public AuthenticationResult AuthenticateUser(User user, string password)
  171. {
  172. AuthenticationResult result = new AuthenticationResult();
  173. // When EnableUserProfiles is false, only the default User can login
  174. if (!Configuration.EnableUserProfiles)
  175. {
  176. result.Success = user.Id == GetDefaultUser().Id;
  177. }
  178. else if (string.IsNullOrEmpty(user.Password))
  179. {
  180. result.Success = true;
  181. }
  182. else
  183. {
  184. result.Success = GetMD5((password ?? string.Empty)).ToString().Equals(user.Password);
  185. }
  186. // Update LastActivityDate and LastLoginDate, then save
  187. if (result.Success)
  188. {
  189. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  190. SaveUser(user);
  191. }
  192. return result;
  193. }
  194. public async Task ReloadItem(BaseItem item)
  195. {
  196. Folder folder = item as Folder;
  197. if (folder != null && folder.IsRoot)
  198. {
  199. await ReloadRoot().ConfigureAwait(false);
  200. }
  201. else
  202. {
  203. if (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  204. {
  205. await ReloadItem(item.Parent).ConfigureAwait(false);
  206. return;
  207. }
  208. BaseItem newItem = await ItemController.GetItem(item.Path, item.Parent).ConfigureAwait(false);
  209. List<BaseItem> children = item.Parent.Children.ToList();
  210. int index = children.IndexOf(item);
  211. children.RemoveAt(index);
  212. children.Insert(index, newItem);
  213. item.Parent.Children = children.ToArray();
  214. }
  215. }
  216. /// <summary>
  217. /// Finds a library item by Id
  218. /// </summary>
  219. public BaseItem GetItemById(Guid id)
  220. {
  221. if (id == Guid.Empty)
  222. {
  223. return RootFolder;
  224. }
  225. return RootFolder.FindItemById(id);
  226. }
  227. /// <summary>
  228. /// Gets all users within the system
  229. /// </summary>
  230. private IEnumerable<User> GetAllUsers()
  231. {
  232. List<User> list = new List<User>();
  233. // Return a dummy user for now since all calls to get items requre a userId
  234. User user = new User();
  235. user.Name = "Default User";
  236. user.Id = Guid.Parse("5d1cf7fce25943b790d140095457a42b");
  237. list.Add(user);
  238. user = new User();
  239. user.Name = "Abobader";
  240. user.Id = Guid.NewGuid();
  241. user.LastLoginDate = DateTime.UtcNow.AddDays(-1);
  242. user.LastActivityDate = DateTime.UtcNow.AddHours(-3);
  243. user.Password = GetMD5("1234").ToString();
  244. list.Add(user);
  245. user = new User();
  246. user.Name = "Scottisafool";
  247. user.Id = Guid.NewGuid();
  248. list.Add(user);
  249. user = new User();
  250. user.Name = "Redshirt";
  251. user.Id = Guid.NewGuid();
  252. list.Add(user);
  253. /*user = new User();
  254. user.Name = "Test User 4";
  255. user.Id = Guid.NewGuid();
  256. list.Add(user);
  257. user = new User();
  258. user.Name = "Test User 5";
  259. user.Id = Guid.NewGuid();
  260. list.Add(user);
  261. user = new User();
  262. user.Name = "Test User 6";
  263. user.Id = Guid.NewGuid();
  264. list.Add(user);*/
  265. return list;
  266. }
  267. /// <summary>
  268. /// Runs all metadata providers for an entity
  269. /// </summary>
  270. internal async Task ExecuteMetadataProviders(BaseEntity item, ItemResolveEventArgs args, bool allowInternetProviders = true)
  271. {
  272. // Run them sequentially in order of priority
  273. for (int i = 0; i < MetadataProviders.Length; i++)
  274. {
  275. var provider = MetadataProviders[i];
  276. // Skip if internet providers are currently disabled
  277. if (provider.RequiresInternet && (!Configuration.EnableInternetProviders || !allowInternetProviders))
  278. {
  279. continue;
  280. }
  281. // Skip if the provider doesn't support the current item
  282. if (!provider.Supports(item))
  283. {
  284. continue;
  285. }
  286. try
  287. {
  288. await provider.FetchAsync(item, args).ConfigureAwait(false);
  289. }
  290. catch (Exception ex)
  291. {
  292. Logger.LogException(ex);
  293. }
  294. }
  295. }
  296. private void ExtractFFMpeg()
  297. {
  298. ExtractFFMpeg(ApplicationPaths.FFMpegPath);
  299. ExtractFFMpeg(ApplicationPaths.FFProbePath);
  300. }
  301. /// <summary>
  302. /// Run these during Init.
  303. /// Can't run do this on-demand because there will be multiple workers accessing them at once and we'd have to lock them
  304. /// </summary>
  305. private void ExtractFFMpeg(string exe)
  306. {
  307. if (File.Exists(exe))
  308. {
  309. File.Delete(exe);
  310. }
  311. // Extract exe
  312. using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MediaBrowser.Controller.FFMpeg." + Path.GetFileName(exe)))
  313. {
  314. using (FileStream fileStream = new FileStream(exe, FileMode.Create))
  315. {
  316. stream.CopyTo(fileStream);
  317. }
  318. }
  319. }
  320. protected override void DisposeComposableParts()
  321. {
  322. base.DisposeComposableParts();
  323. DisposeProviders();
  324. }
  325. /// <summary>
  326. /// Disposes all providers
  327. /// </summary>
  328. private void DisposeProviders()
  329. {
  330. if (MetadataProviders != null)
  331. {
  332. foreach (var provider in MetadataProviders)
  333. {
  334. provider.Dispose();
  335. }
  336. }
  337. }
  338. }
  339. }