Kernel.cs 14 KB

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