Kernel.cs 12 KB

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