ApplicationHost.cs 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Http;
  11. using System.Net.Sockets;
  12. using System.Reflection;
  13. using System.Runtime.InteropServices;
  14. using System.Security.Cryptography.X509Certificates;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using Emby.Dlna;
  19. using Emby.Dlna.Main;
  20. using Emby.Dlna.Ssdp;
  21. using Emby.Drawing;
  22. using Emby.Notifications;
  23. using Emby.Photos;
  24. using Emby.Server.Implementations.Activity;
  25. using Emby.Server.Implementations.Archiving;
  26. using Emby.Server.Implementations.Channels;
  27. using Emby.Server.Implementations.Collections;
  28. using Emby.Server.Implementations.Configuration;
  29. using Emby.Server.Implementations.Cryptography;
  30. using Emby.Server.Implementations.Data;
  31. using Emby.Server.Implementations.Devices;
  32. using Emby.Server.Implementations.Diagnostics;
  33. using Emby.Server.Implementations.Dto;
  34. using Emby.Server.Implementations.HttpServer;
  35. using Emby.Server.Implementations.HttpServer.Security;
  36. using Emby.Server.Implementations.IO;
  37. using Emby.Server.Implementations.Library;
  38. using Emby.Server.Implementations.LiveTv;
  39. using Emby.Server.Implementations.Localization;
  40. using Emby.Server.Implementations.Net;
  41. using Emby.Server.Implementations.Playlists;
  42. using Emby.Server.Implementations.ScheduledTasks;
  43. using Emby.Server.Implementations.Security;
  44. using Emby.Server.Implementations.Serialization;
  45. using Emby.Server.Implementations.Session;
  46. using Emby.Server.Implementations.SocketSharp;
  47. using Emby.Server.Implementations.TV;
  48. using Emby.Server.Implementations.Updates;
  49. using MediaBrowser.Api;
  50. using MediaBrowser.Common;
  51. using MediaBrowser.Common.Configuration;
  52. using MediaBrowser.Common.Events;
  53. using MediaBrowser.Common.Net;
  54. using MediaBrowser.Common.Plugins;
  55. using MediaBrowser.Common.Updates;
  56. using MediaBrowser.Controller;
  57. using MediaBrowser.Controller.Authentication;
  58. using MediaBrowser.Controller.Channels;
  59. using MediaBrowser.Controller.Chapters;
  60. using MediaBrowser.Controller.Collections;
  61. using MediaBrowser.Controller.Configuration;
  62. using MediaBrowser.Controller.Devices;
  63. using MediaBrowser.Controller.Dlna;
  64. using MediaBrowser.Controller.Drawing;
  65. using MediaBrowser.Controller.Dto;
  66. using MediaBrowser.Controller.Entities;
  67. using MediaBrowser.Controller.Library;
  68. using MediaBrowser.Controller.LiveTv;
  69. using MediaBrowser.Controller.MediaEncoding;
  70. using MediaBrowser.Controller.Net;
  71. using MediaBrowser.Controller.Notifications;
  72. using MediaBrowser.Controller.Persistence;
  73. using MediaBrowser.Controller.Playlists;
  74. using MediaBrowser.Controller.Plugins;
  75. using MediaBrowser.Controller.Providers;
  76. using MediaBrowser.Controller.Resolvers;
  77. using MediaBrowser.Controller.Security;
  78. using MediaBrowser.Controller.Session;
  79. using MediaBrowser.Controller.Sorting;
  80. using MediaBrowser.Controller.Subtitles;
  81. using MediaBrowser.Controller.TV;
  82. using MediaBrowser.LocalMetadata.Savers;
  83. using MediaBrowser.MediaEncoding.BdInfo;
  84. using MediaBrowser.Model.Activity;
  85. using MediaBrowser.Model.Configuration;
  86. using MediaBrowser.Model.Cryptography;
  87. using MediaBrowser.Model.Diagnostics;
  88. using MediaBrowser.Model.Dlna;
  89. using MediaBrowser.Model.Events;
  90. using MediaBrowser.Model.Extensions;
  91. using MediaBrowser.Model.Globalization;
  92. using MediaBrowser.Model.IO;
  93. using MediaBrowser.Model.MediaInfo;
  94. using MediaBrowser.Model.Net;
  95. using MediaBrowser.Model.Serialization;
  96. using MediaBrowser.Model.Services;
  97. using MediaBrowser.Model.System;
  98. using MediaBrowser.Model.Tasks;
  99. using MediaBrowser.Model.Updates;
  100. using MediaBrowser.Providers.Chapters;
  101. using MediaBrowser.Providers.Manager;
  102. using MediaBrowser.Providers.Subtitles;
  103. using MediaBrowser.Providers.TV.TheTVDB;
  104. using MediaBrowser.WebDashboard.Api;
  105. using MediaBrowser.XbmcMetadata.Providers;
  106. using Microsoft.AspNetCore.Builder;
  107. using Microsoft.AspNetCore.Hosting;
  108. using Microsoft.AspNetCore.Http;
  109. using Microsoft.AspNetCore.Http.Extensions;
  110. using Microsoft.Extensions.Configuration;
  111. using Microsoft.Extensions.DependencyInjection;
  112. using Microsoft.Extensions.DependencyInjection.Extensions;
  113. using Microsoft.Extensions.Logging;
  114. using ServiceStack;
  115. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  116. namespace Emby.Server.Implementations
  117. {
  118. /// <summary>
  119. /// Class CompositionRoot.
  120. /// </summary>
  121. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  122. {
  123. private SqliteUserRepository _userRepository;
  124. private SqliteDisplayPreferencesRepository _displayPreferencesRepository;
  125. /// <summary>
  126. /// Gets a value indicating whether this instance can self restart.
  127. /// </summary>
  128. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  129. public abstract bool CanSelfRestart { get; }
  130. public virtual bool CanLaunchWebBrowser
  131. {
  132. get
  133. {
  134. if (!Environment.UserInteractive)
  135. {
  136. return false;
  137. }
  138. if (StartupOptions.IsService)
  139. {
  140. return false;
  141. }
  142. if (OperatingSystem.Id == OperatingSystemId.Windows
  143. || OperatingSystem.Id == OperatingSystemId.Darwin)
  144. {
  145. return true;
  146. }
  147. return false;
  148. }
  149. }
  150. /// <summary>
  151. /// Occurs when [has pending restart changed].
  152. /// </summary>
  153. public event EventHandler HasPendingRestartChanged;
  154. /// <summary>
  155. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  156. /// </summary>
  157. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  158. public bool HasPendingRestart { get; private set; }
  159. /// <inheritdoc />
  160. public bool IsShuttingDown { get; private set; }
  161. /// <summary>
  162. /// Gets or sets the logger.
  163. /// </summary>
  164. /// <value>The logger.</value>
  165. protected ILogger Logger { get; set; }
  166. private IPlugin[] _plugins;
  167. /// <summary>
  168. /// Gets the plugins.
  169. /// </summary>
  170. /// <value>The plugins.</value>
  171. public IPlugin[] Plugins
  172. {
  173. get => _plugins;
  174. protected set => _plugins = value;
  175. }
  176. /// <summary>
  177. /// Gets or sets the logger factory.
  178. /// </summary>
  179. /// <value>The logger factory.</value>
  180. public ILoggerFactory LoggerFactory { get; protected set; }
  181. /// <summary>
  182. /// Gets or sets the application paths.
  183. /// </summary>
  184. /// <value>The application paths.</value>
  185. protected ServerApplicationPaths ApplicationPaths { get; set; }
  186. /// <summary>
  187. /// Gets or sets all concrete types.
  188. /// </summary>
  189. /// <value>All concrete types.</value>
  190. private Type[] _allConcreteTypes;
  191. /// <summary>
  192. /// The disposable parts.
  193. /// </summary>
  194. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  195. /// <summary>
  196. /// Gets the configuration manager.
  197. /// </summary>
  198. /// <value>The configuration manager.</value>
  199. protected IConfigurationManager ConfigurationManager { get; set; }
  200. public IFileSystem FileSystemManager { get; set; }
  201. /// <inheritdoc />
  202. public PackageVersionClass SystemUpdateLevel
  203. {
  204. get
  205. {
  206. #if BETA
  207. return PackageVersionClass.Beta;
  208. #else
  209. return PackageVersionClass.Release;
  210. #endif
  211. }
  212. }
  213. protected IServiceProvider _serviceProvider;
  214. /// <summary>
  215. /// Gets the server configuration manager.
  216. /// </summary>
  217. /// <value>The server configuration manager.</value>
  218. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  219. /// <summary>
  220. /// Gets or sets the user manager.
  221. /// </summary>
  222. /// <value>The user manager.</value>
  223. public IUserManager UserManager { get; set; }
  224. /// <summary>
  225. /// Gets or sets the library manager.
  226. /// </summary>
  227. /// <value>The library manager.</value>
  228. internal ILibraryManager LibraryManager { get; set; }
  229. /// <summary>
  230. /// Gets or sets the directory watchers.
  231. /// </summary>
  232. /// <value>The directory watchers.</value>
  233. private ILibraryMonitor LibraryMonitor { get; set; }
  234. /// <summary>
  235. /// Gets or sets the provider manager.
  236. /// </summary>
  237. /// <value>The provider manager.</value>
  238. private IProviderManager ProviderManager { get; set; }
  239. /// <summary>
  240. /// Gets or sets the HTTP server.
  241. /// </summary>
  242. /// <value>The HTTP server.</value>
  243. private IHttpServer HttpServer { get; set; }
  244. private IDtoService DtoService { get; set; }
  245. public IImageProcessor ImageProcessor { get; set; }
  246. /// <summary>
  247. /// Gets or sets the media encoder.
  248. /// </summary>
  249. /// <value>The media encoder.</value>
  250. private IMediaEncoder MediaEncoder { get; set; }
  251. private ISubtitleEncoder SubtitleEncoder { get; set; }
  252. private ISessionManager SessionManager { get; set; }
  253. private ILiveTvManager LiveTvManager { get; set; }
  254. public LocalizationManager LocalizationManager { get; set; }
  255. private IEncodingManager EncodingManager { get; set; }
  256. private IChannelManager ChannelManager { get; set; }
  257. /// <summary>
  258. /// Gets or sets the user data repository.
  259. /// </summary>
  260. /// <value>The user data repository.</value>
  261. private IUserDataManager UserDataManager { get; set; }
  262. internal SqliteItemRepository ItemRepository { get; set; }
  263. private INotificationManager NotificationManager { get; set; }
  264. private ISubtitleManager SubtitleManager { get; set; }
  265. private IChapterManager ChapterManager { get; set; }
  266. private IDeviceManager DeviceManager { get; set; }
  267. internal IUserViewManager UserViewManager { get; set; }
  268. private IAuthenticationRepository AuthenticationRepository { get; set; }
  269. private ITVSeriesManager TVSeriesManager { get; set; }
  270. private ICollectionManager CollectionManager { get; set; }
  271. private IMediaSourceManager MediaSourceManager { get; set; }
  272. private readonly IConfiguration _configuration;
  273. /// <summary>
  274. /// Gets or sets the installation manager.
  275. /// </summary>
  276. /// <value>The installation manager.</value>
  277. protected IInstallationManager InstallationManager { get; private set; }
  278. protected IAuthService AuthService { get; private set; }
  279. public IStartupOptions StartupOptions { get; }
  280. internal IImageEncoder ImageEncoder { get; private set; }
  281. protected IProcessFactory ProcessFactory { get; private set; }
  282. protected readonly IXmlSerializer XmlSerializer;
  283. protected ISocketFactory SocketFactory { get; private set; }
  284. protected ITaskManager TaskManager { get; private set; }
  285. public IHttpClient HttpClient { get; private set; }
  286. protected INetworkManager NetworkManager { get; set; }
  287. public IJsonSerializer JsonSerializer { get; private set; }
  288. protected IIsoManager IsoManager { get; private set; }
  289. /// <summary>
  290. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  291. /// </summary>
  292. public ApplicationHost(
  293. ServerApplicationPaths applicationPaths,
  294. ILoggerFactory loggerFactory,
  295. IStartupOptions options,
  296. IFileSystem fileSystem,
  297. IImageEncoder imageEncoder,
  298. INetworkManager networkManager,
  299. IConfiguration configuration)
  300. {
  301. _configuration = configuration;
  302. XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory);
  303. NetworkManager = networkManager;
  304. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  305. ApplicationPaths = applicationPaths;
  306. LoggerFactory = loggerFactory;
  307. FileSystemManager = fileSystem;
  308. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager);
  309. Logger = LoggerFactory.CreateLogger("App");
  310. StartupOptions = options;
  311. ImageEncoder = imageEncoder;
  312. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  313. NetworkManager.NetworkChanged += OnNetworkChanged;
  314. }
  315. public string ExpandVirtualPath(string path)
  316. {
  317. var appPaths = ApplicationPaths;
  318. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  319. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  320. }
  321. public string ReverseVirtualPath(string path)
  322. {
  323. var appPaths = ApplicationPaths;
  324. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  325. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  326. }
  327. private string[] GetConfiguredLocalSubnets()
  328. {
  329. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  330. }
  331. private void OnNetworkChanged(object sender, EventArgs e)
  332. {
  333. _validAddressResults.Clear();
  334. }
  335. public string ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
  336. /// <summary>
  337. /// Gets the current application user agent.
  338. /// </summary>
  339. /// <value>The application user agent.</value>
  340. public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersion;
  341. /// <summary>
  342. /// Gets the email address for use within a comment section of a user agent field.
  343. /// Presently used to provide contact information to MusicBrainz service.
  344. /// </summary>
  345. public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
  346. /// <summary>
  347. /// Gets the current application name.
  348. /// </summary>
  349. /// <value>The application name.</value>
  350. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  351. private DeviceId _deviceId;
  352. public string SystemId
  353. {
  354. get
  355. {
  356. if (_deviceId == null)
  357. {
  358. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  359. }
  360. return _deviceId.Value;
  361. }
  362. }
  363. /// <summary>
  364. /// Gets the name.
  365. /// </summary>
  366. /// <value>The name.</value>
  367. public string Name => ApplicationProductName;
  368. /// <summary>
  369. /// Creates an instance of type and resolves all constructor dependencies
  370. /// </summary>
  371. /// <param name="type">The type.</param>
  372. /// <returns>System.Object.</returns>
  373. public object CreateInstance(Type type)
  374. => ActivatorUtilities.CreateInstance(_serviceProvider, type);
  375. /// <summary>
  376. /// Creates an instance of type and resolves all constructor dependencies
  377. /// </summary>
  378. /// /// <typeparam name="T">The type.</typeparam>
  379. /// <returns>T.</returns>
  380. public T CreateInstance<T>()
  381. => ActivatorUtilities.CreateInstance<T>(_serviceProvider);
  382. /// <summary>
  383. /// Creates the instance safe.
  384. /// </summary>
  385. /// <param name="type">The type.</param>
  386. /// <returns>System.Object.</returns>
  387. protected object CreateInstanceSafe(Type type)
  388. {
  389. try
  390. {
  391. Logger.LogDebug("Creating instance of {Type}", type);
  392. return ActivatorUtilities.CreateInstance(_serviceProvider, type);
  393. }
  394. catch (Exception ex)
  395. {
  396. Logger.LogError(ex, "Error creating {Type}", type);
  397. return null;
  398. }
  399. }
  400. /// <summary>
  401. /// Resolves this instance.
  402. /// </summary>
  403. /// <typeparam name="T">The type</typeparam>
  404. /// <returns>``0.</returns>
  405. public T Resolve<T>() => _serviceProvider.GetService<T>();
  406. /// <summary>
  407. /// Gets the export types.
  408. /// </summary>
  409. /// <typeparam name="T">The type</typeparam>
  410. /// <returns>IEnumerable{Type}.</returns>
  411. public IEnumerable<Type> GetExportTypes<T>()
  412. {
  413. var currentType = typeof(T);
  414. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  415. }
  416. /// <inheritdoc />
  417. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  418. {
  419. var parts = GetExportTypes<T>()
  420. .Select(CreateInstanceSafe)
  421. .Where(i => i != null)
  422. .Cast<T>()
  423. .ToList(); // Convert to list so this isn't executed for each iteration
  424. if (manageLifetime)
  425. {
  426. lock (_disposableParts)
  427. {
  428. _disposableParts.AddRange(parts.OfType<IDisposable>());
  429. }
  430. }
  431. return parts;
  432. }
  433. /// <summary>
  434. /// Runs the startup tasks.
  435. /// </summary>
  436. /// <returns><see cref="Task" />.</returns>
  437. public async Task RunStartupTasksAsync()
  438. {
  439. Logger.LogInformation("Running startup tasks");
  440. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  441. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  442. MediaEncoder.SetFFmpegPath();
  443. Logger.LogInformation("ServerId: {0}", SystemId);
  444. var entryPoints = GetExports<IServerEntryPoint>();
  445. var stopWatch = new Stopwatch();
  446. stopWatch.Start();
  447. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  448. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  449. Logger.LogInformation("Core startup complete");
  450. HttpServer.GlobalResponse = null;
  451. stopWatch.Restart();
  452. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  453. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  454. stopWatch.Stop();
  455. }
  456. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  457. {
  458. foreach (var entryPoint in entryPoints)
  459. {
  460. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  461. {
  462. continue;
  463. }
  464. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  465. yield return entryPoint.RunAsync();
  466. }
  467. }
  468. public async Task InitAsync(IServiceCollection serviceCollection)
  469. {
  470. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  471. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  472. // Safeguard against invalid configuration
  473. if (HttpPort == HttpsPort)
  474. {
  475. HttpPort = ServerConfiguration.DefaultHttpPort;
  476. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  477. }
  478. JsonSerializer = new JsonSerializer(FileSystemManager);
  479. if (Plugins != null)
  480. {
  481. var pluginBuilder = new StringBuilder();
  482. foreach (var plugin in Plugins)
  483. {
  484. pluginBuilder.AppendLine(
  485. string.Format(
  486. CultureInfo.InvariantCulture,
  487. "{0} {1}",
  488. plugin.Name,
  489. plugin.Version));
  490. }
  491. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  492. }
  493. DiscoverTypes();
  494. await RegisterResources(serviceCollection).ConfigureAwait(false);
  495. FindParts();
  496. string contentRoot = ServerConfigurationManager.Configuration.DashboardSourcePath;
  497. if (string.IsNullOrEmpty(contentRoot))
  498. {
  499. contentRoot = ServerConfigurationManager.ApplicationPaths.WebPath;
  500. }
  501. var host = new WebHostBuilder()
  502. .UseKestrel(options =>
  503. {
  504. var addresses = ServerConfigurationManager
  505. .Configuration
  506. .LocalNetworkAddresses
  507. .Select(NormalizeConfiguredLocalAddress)
  508. .Where(i => i != null)
  509. .ToList();
  510. if (addresses.Any())
  511. {
  512. foreach (var address in addresses)
  513. {
  514. Logger.LogInformation("Kestrel listening on {ipaddr}", address);
  515. options.Listen(address, HttpPort);
  516. if (EnableHttps && Certificate != null)
  517. {
  518. options.Listen(address, HttpsPort, listenOptions => listenOptions.UseHttps(Certificate));
  519. }
  520. }
  521. }
  522. else
  523. {
  524. Logger.LogInformation("Kestrel listening on all interfaces");
  525. options.ListenAnyIP(HttpPort);
  526. if (EnableHttps && Certificate != null)
  527. {
  528. options.ListenAnyIP(HttpsPort, listenOptions => listenOptions.UseHttps(Certificate));
  529. }
  530. }
  531. })
  532. .UseContentRoot(contentRoot)
  533. .ConfigureServices(services =>
  534. {
  535. services.AddResponseCompression();
  536. services.AddHttpContextAccessor();
  537. })
  538. .Configure(app =>
  539. {
  540. app.UseWebSockets();
  541. app.UseResponseCompression();
  542. // TODO app.UseMiddleware<WebSocketMiddleware>();
  543. app.Use(ExecuteWebsocketHandlerAsync);
  544. app.Use(ExecuteHttpHandlerAsync);
  545. })
  546. .Build();
  547. try
  548. {
  549. await host.StartAsync().ConfigureAwait(false);
  550. }
  551. catch
  552. {
  553. Logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in system.xml and try again.");
  554. throw;
  555. }
  556. }
  557. private async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func<Task> next)
  558. {
  559. if (!context.WebSockets.IsWebSocketRequest)
  560. {
  561. await next().ConfigureAwait(false);
  562. return;
  563. }
  564. await HttpServer.ProcessWebSocketRequest(context).ConfigureAwait(false);
  565. }
  566. private async Task ExecuteHttpHandlerAsync(HttpContext context, Func<Task> next)
  567. {
  568. if (context.WebSockets.IsWebSocketRequest)
  569. {
  570. await next().ConfigureAwait(false);
  571. return;
  572. }
  573. var request = context.Request;
  574. var response = context.Response;
  575. var localPath = context.Request.Path.ToString();
  576. var req = new WebSocketSharpRequest(request, response, request.Path, Logger);
  577. await HttpServer.RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, context.RequestAborted).ConfigureAwait(false);
  578. }
  579. /// <summary>
  580. /// Registers resources that classes will depend on
  581. /// </summary>
  582. protected async Task RegisterResources(IServiceCollection serviceCollection)
  583. {
  584. serviceCollection.AddMemoryCache();
  585. serviceCollection.AddSingleton(ConfigurationManager);
  586. serviceCollection.AddSingleton<IApplicationHost>(this);
  587. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  588. serviceCollection.AddSingleton<IConfiguration>(_configuration);
  589. serviceCollection.AddSingleton(JsonSerializer);
  590. serviceCollection.AddSingleton(LoggerFactory);
  591. serviceCollection.AddLogging();
  592. serviceCollection.AddSingleton(Logger);
  593. serviceCollection.AddSingleton(FileSystemManager);
  594. serviceCollection.AddSingleton<TvDbClientManager>();
  595. HttpClient = new HttpClientManager.HttpClientManager(
  596. ApplicationPaths,
  597. LoggerFactory.CreateLogger<HttpClientManager.HttpClientManager>(),
  598. FileSystemManager,
  599. () => ApplicationUserAgent);
  600. serviceCollection.AddSingleton(HttpClient);
  601. serviceCollection.AddSingleton(NetworkManager);
  602. IsoManager = new IsoManager();
  603. serviceCollection.AddSingleton(IsoManager);
  604. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory, FileSystemManager);
  605. serviceCollection.AddSingleton(TaskManager);
  606. serviceCollection.AddSingleton(XmlSerializer);
  607. ProcessFactory = new ProcessFactory();
  608. serviceCollection.AddSingleton(ProcessFactory);
  609. serviceCollection.AddSingleton(typeof(IStreamHelper), typeof(StreamHelper));
  610. serviceCollection.AddSingleton(typeof(ICryptoProvider), typeof(CryptographyProvider));
  611. SocketFactory = new SocketFactory();
  612. serviceCollection.AddSingleton(SocketFactory);
  613. serviceCollection.AddSingleton(typeof(IInstallationManager), typeof(InstallationManager));
  614. serviceCollection.AddSingleton(typeof(IZipClient), typeof(ZipClient));
  615. serviceCollection.AddSingleton(typeof(IHttpResultFactory), typeof(HttpResultFactory));
  616. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  617. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  618. serviceCollection.AddSingleton(ServerConfigurationManager);
  619. LocalizationManager = new LocalizationManager(ServerConfigurationManager, JsonSerializer, LoggerFactory.CreateLogger<LocalizationManager>());
  620. await LocalizationManager.LoadAll().ConfigureAwait(false);
  621. serviceCollection.AddSingleton<ILocalizationManager>(LocalizationManager);
  622. serviceCollection.AddSingleton<IBlurayExaminer>(new BdInfoExaminer(FileSystemManager));
  623. UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
  624. serviceCollection.AddSingleton(UserDataManager);
  625. _displayPreferencesRepository = new SqliteDisplayPreferencesRepository(
  626. LoggerFactory.CreateLogger<SqliteDisplayPreferencesRepository>(),
  627. ApplicationPaths,
  628. FileSystemManager);
  629. serviceCollection.AddSingleton<IDisplayPreferencesRepository>(_displayPreferencesRepository);
  630. ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, LoggerFactory.CreateLogger<SqliteItemRepository>(), LocalizationManager);
  631. serviceCollection.AddSingleton<IItemRepository>(ItemRepository);
  632. AuthenticationRepository = GetAuthenticationRepository();
  633. serviceCollection.AddSingleton(AuthenticationRepository);
  634. _userRepository = GetUserRepository();
  635. UserManager = new UserManager(LoggerFactory.CreateLogger<UserManager>(), _userRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager);
  636. serviceCollection.AddSingleton(UserManager);
  637. LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
  638. serviceCollection.AddSingleton(LibraryManager);
  639. // TODO wtaylor: investigate use of second music manager
  640. var musicManager = new MusicManager(LibraryManager);
  641. serviceCollection.AddSingleton<IMusicManager>(new MusicManager(LibraryManager));
  642. LibraryMonitor = new LibraryMonitor(LoggerFactory, LibraryManager, ServerConfigurationManager, FileSystemManager);
  643. serviceCollection.AddSingleton(LibraryMonitor);
  644. serviceCollection.AddSingleton<ISearchEngine>(new SearchEngine(LoggerFactory, LibraryManager, UserManager));
  645. CertificateInfo = GetCertificateInfo(true);
  646. Certificate = GetCertificate(CertificateInfo);
  647. HttpServer = new HttpListenerHost(
  648. this,
  649. LoggerFactory.CreateLogger<HttpListenerHost>(),
  650. ServerConfigurationManager,
  651. _configuration,
  652. NetworkManager,
  653. JsonSerializer,
  654. XmlSerializer,
  655. CreateHttpListener())
  656. {
  657. GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading")
  658. };
  659. serviceCollection.AddSingleton(HttpServer);
  660. ImageProcessor = new ImageProcessor(LoggerFactory.CreateLogger<ImageProcessor>(), ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
  661. serviceCollection.AddSingleton(ImageProcessor);
  662. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  663. serviceCollection.AddSingleton(TVSeriesManager);
  664. DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager);
  665. serviceCollection.AddSingleton(DeviceManager);
  666. MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, () => MediaEncoder);
  667. serviceCollection.AddSingleton(MediaSourceManager);
  668. SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
  669. serviceCollection.AddSingleton(SubtitleManager);
  670. ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
  671. serviceCollection.AddSingleton(ProviderManager);
  672. DtoService = new DtoService(LoggerFactory, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ProviderManager, this, () => MediaSourceManager, () => LiveTvManager);
  673. serviceCollection.AddSingleton(DtoService);
  674. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, ProviderManager);
  675. serviceCollection.AddSingleton(ChannelManager);
  676. SessionManager = new SessionManager(UserDataManager, LoggerFactory, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, this, AuthenticationRepository, DeviceManager, MediaSourceManager);
  677. serviceCollection.AddSingleton(SessionManager);
  678. serviceCollection.AddSingleton<IDlnaManager>(
  679. new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory, JsonSerializer, this));
  680. CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager);
  681. serviceCollection.AddSingleton(CollectionManager);
  682. serviceCollection.AddSingleton(typeof(IPlaylistManager), typeof(PlaylistManager));
  683. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, FileSystemManager, () => ChannelManager);
  684. serviceCollection.AddSingleton(LiveTvManager);
  685. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  686. serviceCollection.AddSingleton(UserViewManager);
  687. NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager);
  688. serviceCollection.AddSingleton(NotificationManager);
  689. serviceCollection.AddSingleton<IDeviceDiscovery>(
  690. new DeviceDiscovery(LoggerFactory, ServerConfigurationManager, SocketFactory));
  691. ChapterManager = new ChapterManager(LibraryManager, LoggerFactory, ServerConfigurationManager, ItemRepository);
  692. serviceCollection.AddSingleton(ChapterManager);
  693. MediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  694. LoggerFactory,
  695. JsonSerializer,
  696. StartupOptions.FFmpegPath,
  697. ServerConfigurationManager,
  698. FileSystemManager,
  699. () => SubtitleEncoder,
  700. () => MediaSourceManager,
  701. ProcessFactory,
  702. 5000,
  703. LocalizationManager);
  704. serviceCollection.AddSingleton(MediaEncoder);
  705. EncodingManager = new MediaEncoder.EncodingManager(FileSystemManager, LoggerFactory, MediaEncoder, ChapterManager, LibraryManager);
  706. serviceCollection.AddSingleton(EncodingManager);
  707. var activityLogRepo = GetActivityLogRepository();
  708. serviceCollection.AddSingleton(activityLogRepo);
  709. serviceCollection.AddSingleton<IActivityManager>(new ActivityManager(LoggerFactory, activityLogRepo, UserManager));
  710. var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
  711. serviceCollection.AddSingleton<IAuthorizationContext>(authContext);
  712. serviceCollection.AddSingleton<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  713. AuthService = new AuthService(authContext, ServerConfigurationManager, SessionManager, NetworkManager);
  714. serviceCollection.AddSingleton(AuthService);
  715. SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory, ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory);
  716. serviceCollection.AddSingleton(SubtitleEncoder);
  717. serviceCollection.AddSingleton(typeof(IResourceFileManager), typeof(ResourceFileManager));
  718. _displayPreferencesRepository.Initialize();
  719. var userDataRepo = new SqliteUserDataRepository(LoggerFactory, ApplicationPaths);
  720. SetStaticProperties();
  721. ((UserManager)UserManager).Initialize();
  722. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  723. ItemRepository.Initialize(userDataRepo, UserManager);
  724. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  725. _serviceProvider = serviceCollection.BuildServiceProvider();
  726. }
  727. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  728. {
  729. // Distinct these to prevent users from reporting problems that aren't actually problems
  730. var commandLineArgs = Environment
  731. .GetCommandLineArgs()
  732. .Distinct();
  733. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  734. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  735. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  736. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  737. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  738. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  739. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  740. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  741. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  742. }
  743. private X509Certificate2 GetCertificate(CertificateInfo info)
  744. {
  745. var certificateLocation = info?.Path;
  746. if (string.IsNullOrWhiteSpace(certificateLocation))
  747. {
  748. return null;
  749. }
  750. try
  751. {
  752. if (!File.Exists(certificateLocation))
  753. {
  754. return null;
  755. }
  756. // Don't use an empty string password
  757. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  758. var localCert = new X509Certificate2(certificateLocation, password);
  759. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  760. if (!localCert.HasPrivateKey)
  761. {
  762. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  763. return null;
  764. }
  765. return localCert;
  766. }
  767. catch (Exception ex)
  768. {
  769. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  770. return null;
  771. }
  772. }
  773. /// <summary>
  774. /// Gets the user repository.
  775. /// </summary>
  776. /// <returns><see cref="Task{SqliteUserRepository}" />.</returns>
  777. private SqliteUserRepository GetUserRepository()
  778. {
  779. var repo = new SqliteUserRepository(
  780. LoggerFactory.CreateLogger<SqliteUserRepository>(),
  781. ApplicationPaths);
  782. repo.Initialize();
  783. return repo;
  784. }
  785. private IAuthenticationRepository GetAuthenticationRepository()
  786. {
  787. var repo = new AuthenticationRepository(LoggerFactory, ServerConfigurationManager);
  788. repo.Initialize();
  789. return repo;
  790. }
  791. private IActivityRepository GetActivityLogRepository()
  792. {
  793. var repo = new ActivityRepository(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager);
  794. repo.Initialize();
  795. return repo;
  796. }
  797. /// <summary>
  798. /// Dirty hacks
  799. /// </summary>
  800. private void SetStaticProperties()
  801. {
  802. ItemRepository.ImageProcessor = ImageProcessor;
  803. // For now there's no real way to inject these properly
  804. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  805. BaseItem.ConfigurationManager = ServerConfigurationManager;
  806. BaseItem.LibraryManager = LibraryManager;
  807. BaseItem.ProviderManager = ProviderManager;
  808. BaseItem.LocalizationManager = LocalizationManager;
  809. BaseItem.ItemRepository = ItemRepository;
  810. User.UserManager = UserManager;
  811. BaseItem.FileSystem = FileSystemManager;
  812. BaseItem.UserDataManager = UserDataManager;
  813. BaseItem.ChannelManager = ChannelManager;
  814. Video.LiveTvManager = LiveTvManager;
  815. Folder.UserViewManager = UserViewManager;
  816. UserView.TVSeriesManager = TVSeriesManager;
  817. UserView.CollectionManager = CollectionManager;
  818. BaseItem.MediaSourceManager = MediaSourceManager;
  819. CollectionFolder.XmlSerializer = XmlSerializer;
  820. CollectionFolder.JsonSerializer = JsonSerializer;
  821. CollectionFolder.ApplicationHost = this;
  822. AuthenticatedAttribute.AuthService = AuthService;
  823. }
  824. private async void PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> args)
  825. {
  826. string dir = Path.Combine(ApplicationPaths.PluginsPath, args.Argument.name);
  827. var types = Directory.EnumerateFiles(dir, "*.dll", SearchOption.AllDirectories)
  828. .Select(x => Assembly.LoadFrom(x))
  829. .SelectMany(x => x.ExportedTypes)
  830. .Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface && !x.IsGenericType)
  831. .ToArray();
  832. int oldLen = _allConcreteTypes.Length;
  833. Array.Resize(ref _allConcreteTypes, oldLen + types.Length);
  834. types.CopyTo(_allConcreteTypes, oldLen);
  835. var plugins = types.Where(x => x.IsAssignableFrom(typeof(IPlugin)))
  836. .Select(CreateInstanceSafe)
  837. .Where(x => x != null)
  838. .Cast<IPlugin>()
  839. .Select(LoadPlugin)
  840. .Where(x => x != null)
  841. .ToArray();
  842. oldLen = _plugins.Length;
  843. Array.Resize(ref _plugins, oldLen + plugins.Length);
  844. plugins.CopyTo(_plugins, oldLen);
  845. var entries = types.Where(x => x.IsAssignableFrom(typeof(IServerEntryPoint)))
  846. .Select(CreateInstanceSafe)
  847. .Where(x => x != null)
  848. .Cast<IServerEntryPoint>()
  849. .ToList();
  850. await Task.WhenAll(StartEntryPoints(entries, true)).ConfigureAwait(false);
  851. await Task.WhenAll(StartEntryPoints(entries, false)).ConfigureAwait(false);
  852. }
  853. /// <summary>
  854. /// Finds the parts.
  855. /// </summary>
  856. protected void FindParts()
  857. {
  858. InstallationManager = _serviceProvider.GetService<IInstallationManager>();
  859. InstallationManager.PluginInstalled += PluginInstalled;
  860. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  861. {
  862. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  863. ConfigurationManager.SaveConfiguration();
  864. }
  865. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  866. Plugins = GetExports<IPlugin>()
  867. .Select(LoadPlugin)
  868. .Where(i => i != null)
  869. .ToArray();
  870. HttpServer.Init(GetExports<IService>(false), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  871. LibraryManager.AddParts(
  872. GetExports<IResolverIgnoreRule>(),
  873. GetExports<IItemResolver>(),
  874. GetExports<IIntroProvider>(),
  875. GetExports<IBaseItemComparer>(),
  876. GetExports<ILibraryPostScanTask>());
  877. ProviderManager.AddParts(
  878. GetExports<IImageProvider>(),
  879. GetExports<IMetadataService>(),
  880. GetExports<IMetadataProvider>(),
  881. GetExports<IMetadataSaver>(),
  882. GetExports<IExternalId>());
  883. ImageProcessor.ImageEnhancers = GetExports<IImageEnhancer>();
  884. LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  885. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  886. ChannelManager.AddParts(GetExports<IChannel>());
  887. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  888. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  889. UserManager.AddParts(GetExports<IAuthenticationProvider>(), GetExports<IPasswordResetProvider>());
  890. IsoManager.AddParts(GetExports<IIsoMounter>());
  891. }
  892. private IPlugin LoadPlugin(IPlugin plugin)
  893. {
  894. try
  895. {
  896. if (plugin is IPluginAssembly assemblyPlugin)
  897. {
  898. var assembly = plugin.GetType().Assembly;
  899. var assemblyName = assembly.GetName();
  900. var assemblyFilePath = assembly.Location;
  901. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  902. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  903. try
  904. {
  905. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  906. if (idAttributes.Length > 0)
  907. {
  908. var attribute = (GuidAttribute)idAttributes[0];
  909. var assemblyId = new Guid(attribute.Value);
  910. assemblyPlugin.SetId(assemblyId);
  911. }
  912. }
  913. catch (Exception ex)
  914. {
  915. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  916. }
  917. }
  918. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  919. {
  920. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  921. }
  922. }
  923. catch (Exception ex)
  924. {
  925. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  926. return null;
  927. }
  928. return plugin;
  929. }
  930. /// <summary>
  931. /// Discovers the types.
  932. /// </summary>
  933. protected void DiscoverTypes()
  934. {
  935. Logger.LogInformation("Loading assemblies");
  936. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  937. }
  938. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  939. {
  940. foreach (var ass in assemblies)
  941. {
  942. Type[] exportedTypes;
  943. try
  944. {
  945. exportedTypes = ass.GetExportedTypes();
  946. }
  947. catch (TypeLoadException ex)
  948. {
  949. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  950. continue;
  951. }
  952. foreach (Type type in exportedTypes)
  953. {
  954. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  955. {
  956. yield return type;
  957. }
  958. }
  959. }
  960. }
  961. private CertificateInfo CertificateInfo { get; set; }
  962. protected X509Certificate2 Certificate { get; private set; }
  963. private IEnumerable<string> GetUrlPrefixes()
  964. {
  965. var hosts = new[] { "+" };
  966. return hosts.SelectMany(i =>
  967. {
  968. var prefixes = new List<string>
  969. {
  970. "http://" + i + ":" + HttpPort + "/"
  971. };
  972. if (CertificateInfo != null)
  973. {
  974. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  975. }
  976. return prefixes;
  977. });
  978. }
  979. protected IHttpListener CreateHttpListener() => new WebSocketSharpListener(Logger);
  980. private CertificateInfo GetCertificateInfo(bool generateCertificate)
  981. {
  982. // Custom cert
  983. return new CertificateInfo
  984. {
  985. Path = ServerConfigurationManager.Configuration.CertificatePath,
  986. Password = ServerConfigurationManager.Configuration.CertificatePassword
  987. };
  988. }
  989. /// <summary>
  990. /// Called when [configuration updated].
  991. /// </summary>
  992. /// <param name="sender">The sender.</param>
  993. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  994. protected void OnConfigurationUpdated(object sender, EventArgs e)
  995. {
  996. var requiresRestart = false;
  997. // Don't do anything if these haven't been set yet
  998. if (HttpPort != 0 && HttpsPort != 0)
  999. {
  1000. // Need to restart if ports have changed
  1001. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  1002. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  1003. {
  1004. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  1005. {
  1006. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  1007. ServerConfigurationManager.SaveConfiguration();
  1008. requiresRestart = true;
  1009. }
  1010. }
  1011. }
  1012. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  1013. {
  1014. requiresRestart = true;
  1015. }
  1016. var currentCertPath = CertificateInfo?.Path;
  1017. var newCertInfo = GetCertificateInfo(false);
  1018. var newCertPath = newCertInfo?.Path;
  1019. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  1020. {
  1021. requiresRestart = true;
  1022. }
  1023. if (requiresRestart)
  1024. {
  1025. Logger.LogInformation("App needs to be restarted due to configuration change.");
  1026. NotifyPendingRestart();
  1027. }
  1028. }
  1029. /// <summary>
  1030. /// Notifies that the kernel that a change has been made that requires a restart
  1031. /// </summary>
  1032. public void NotifyPendingRestart()
  1033. {
  1034. Logger.LogInformation("App needs to be restarted.");
  1035. var changed = !HasPendingRestart;
  1036. HasPendingRestart = true;
  1037. if (changed)
  1038. {
  1039. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  1040. }
  1041. }
  1042. /// <summary>
  1043. /// Restarts this instance.
  1044. /// </summary>
  1045. public void Restart()
  1046. {
  1047. if (!CanSelfRestart)
  1048. {
  1049. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  1050. }
  1051. if (IsShuttingDown)
  1052. {
  1053. return;
  1054. }
  1055. IsShuttingDown = true;
  1056. Task.Run(async () =>
  1057. {
  1058. try
  1059. {
  1060. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  1061. }
  1062. catch (Exception ex)
  1063. {
  1064. Logger.LogError(ex, "Error sending server restart notification");
  1065. }
  1066. Logger.LogInformation("Calling RestartInternal");
  1067. RestartInternal();
  1068. });
  1069. }
  1070. protected abstract void RestartInternal();
  1071. /// <summary>
  1072. /// Gets the composable part assemblies.
  1073. /// </summary>
  1074. /// <returns>IEnumerable{Assembly}.</returns>
  1075. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  1076. {
  1077. if (Directory.Exists(ApplicationPaths.PluginsPath))
  1078. {
  1079. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  1080. {
  1081. Assembly plugAss;
  1082. try
  1083. {
  1084. plugAss = Assembly.LoadFrom(file);
  1085. }
  1086. catch (FileLoadException ex)
  1087. {
  1088. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  1089. continue;
  1090. }
  1091. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  1092. yield return plugAss;
  1093. }
  1094. }
  1095. // Include composable parts in the Api assembly
  1096. yield return typeof(ApiEntryPoint).Assembly;
  1097. // Include composable parts in the Dashboard assembly
  1098. yield return typeof(DashboardService).Assembly;
  1099. // Include composable parts in the Model assembly
  1100. yield return typeof(SystemInfo).Assembly;
  1101. // Include composable parts in the Common assembly
  1102. yield return typeof(IApplicationHost).Assembly;
  1103. // Include composable parts in the Controller assembly
  1104. yield return typeof(IServerApplicationHost).Assembly;
  1105. // Include composable parts in the Providers assembly
  1106. yield return typeof(ProviderUtils).Assembly;
  1107. // Include composable parts in the Photos assembly
  1108. yield return typeof(PhotoProvider).Assembly;
  1109. // Emby.Server implementations
  1110. yield return typeof(InstallationManager).Assembly;
  1111. // MediaEncoding
  1112. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  1113. // Dlna
  1114. yield return typeof(DlnaEntryPoint).Assembly;
  1115. // Local metadata
  1116. yield return typeof(BoxSetXmlSaver).Assembly;
  1117. // Notifications
  1118. yield return typeof(NotificationManager).Assembly;
  1119. // Xbmc
  1120. yield return typeof(ArtistNfoProvider).Assembly;
  1121. foreach (var i in GetAssembliesWithPartsInternal())
  1122. {
  1123. yield return i;
  1124. }
  1125. }
  1126. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  1127. /// <summary>
  1128. /// Gets the system status.
  1129. /// </summary>
  1130. /// <param name="cancellationToken">The cancellation token</param>
  1131. /// <returns>SystemInfo.</returns>
  1132. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  1133. {
  1134. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1135. return new SystemInfo
  1136. {
  1137. HasPendingRestart = HasPendingRestart,
  1138. IsShuttingDown = IsShuttingDown,
  1139. Version = ApplicationVersion,
  1140. WebSocketPortNumber = HttpPort,
  1141. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  1142. Id = SystemId,
  1143. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1144. WebPath = ApplicationPaths.WebPath,
  1145. LogPath = ApplicationPaths.LogDirectoryPath,
  1146. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  1147. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1148. CachePath = ApplicationPaths.CachePath,
  1149. HttpServerPortNumber = HttpPort,
  1150. SupportsHttps = SupportsHttps,
  1151. HttpsPortNumber = HttpsPort,
  1152. OperatingSystem = OperatingSystem.Id.ToString(),
  1153. OperatingSystemDisplayName = OperatingSystem.Name,
  1154. CanSelfRestart = CanSelfRestart,
  1155. CanLaunchWebBrowser = CanLaunchWebBrowser,
  1156. HasUpdateAvailable = HasUpdateAvailable,
  1157. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  1158. ServerName = FriendlyName,
  1159. LocalAddress = localAddress,
  1160. SupportsLibraryMonitor = true,
  1161. EncoderLocation = MediaEncoder.EncoderLocation,
  1162. SystemArchitecture = RuntimeInformation.OSArchitecture,
  1163. SystemUpdateLevel = SystemUpdateLevel,
  1164. PackageName = StartupOptions.PackageName
  1165. };
  1166. }
  1167. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  1168. => NetworkManager.GetMacAddresses()
  1169. .Select(i => new WakeOnLanInfo(i))
  1170. .ToList();
  1171. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1172. {
  1173. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1174. return new PublicSystemInfo
  1175. {
  1176. Version = ApplicationVersion,
  1177. ProductName = ApplicationProductName,
  1178. Id = SystemId,
  1179. OperatingSystem = OperatingSystem.Id.ToString(),
  1180. ServerName = FriendlyName,
  1181. LocalAddress = localAddress
  1182. };
  1183. }
  1184. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1185. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1186. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1187. {
  1188. try
  1189. {
  1190. // Return the first matched address, if found, or the first known local address
  1191. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1192. foreach (var address in addresses)
  1193. {
  1194. return GetLocalApiUrl(address);
  1195. }
  1196. return null;
  1197. }
  1198. catch (Exception ex)
  1199. {
  1200. Logger.LogError(ex, "Error getting local Ip address information");
  1201. }
  1202. return null;
  1203. }
  1204. /// <summary>
  1205. /// Removes the scope id from IPv6 addresses.
  1206. /// </summary>
  1207. /// <param name="address">The IPv6 address.</param>
  1208. /// <returns>The IPv6 address without the scope id.</returns>
  1209. private string RemoveScopeId(string address)
  1210. {
  1211. var index = address.IndexOf('%');
  1212. if (index == -1)
  1213. {
  1214. return address;
  1215. }
  1216. return address.Substring(0, index);
  1217. }
  1218. public string GetLocalApiUrl(IPAddress ipAddress)
  1219. {
  1220. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1221. {
  1222. var str = RemoveScopeId(ipAddress.ToString());
  1223. return GetLocalApiUrl("[" + str + "]");
  1224. }
  1225. return GetLocalApiUrl(ipAddress.ToString());
  1226. }
  1227. public string GetLocalApiUrl(string host)
  1228. {
  1229. if (EnableHttps)
  1230. {
  1231. return string.Format("https://{0}:{1}",
  1232. host,
  1233. HttpsPort.ToString(CultureInfo.InvariantCulture));
  1234. }
  1235. return string.Format("http://{0}:{1}",
  1236. host,
  1237. HttpPort.ToString(CultureInfo.InvariantCulture));
  1238. }
  1239. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1240. {
  1241. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1242. }
  1243. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1244. {
  1245. var addresses = ServerConfigurationManager
  1246. .Configuration
  1247. .LocalNetworkAddresses
  1248. .Select(NormalizeConfiguredLocalAddress)
  1249. .Where(i => i != null)
  1250. .ToList();
  1251. if (addresses.Count == 0)
  1252. {
  1253. addresses.AddRange(NetworkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1254. }
  1255. var resultList = new List<IPAddress>();
  1256. foreach (var address in addresses)
  1257. {
  1258. if (!allowLoopback)
  1259. {
  1260. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1261. {
  1262. continue;
  1263. }
  1264. }
  1265. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1266. if (valid)
  1267. {
  1268. resultList.Add(address);
  1269. if (limit > 0 && resultList.Count >= limit)
  1270. {
  1271. return resultList;
  1272. }
  1273. }
  1274. }
  1275. return resultList;
  1276. }
  1277. private IPAddress NormalizeConfiguredLocalAddress(string address)
  1278. {
  1279. var index = address.Trim('/').IndexOf('/');
  1280. if (index != -1)
  1281. {
  1282. address = address.Substring(index + 1);
  1283. }
  1284. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1285. {
  1286. return result;
  1287. }
  1288. return null;
  1289. }
  1290. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1291. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1292. {
  1293. if (address.Equals(IPAddress.Loopback)
  1294. || address.Equals(IPAddress.IPv6Loopback))
  1295. {
  1296. return true;
  1297. }
  1298. var apiUrl = GetLocalApiUrl(address);
  1299. apiUrl += "/system/ping";
  1300. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1301. {
  1302. return cachedResult;
  1303. }
  1304. try
  1305. {
  1306. using (var response = await HttpClient.SendAsync(
  1307. new HttpRequestOptions
  1308. {
  1309. Url = apiUrl,
  1310. LogErrorResponseBody = false,
  1311. BufferContent = false,
  1312. CancellationToken = cancellationToken
  1313. }, HttpMethod.Post).ConfigureAwait(false))
  1314. {
  1315. using (var reader = new StreamReader(response.Content))
  1316. {
  1317. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1318. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1319. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1320. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1321. return valid;
  1322. }
  1323. }
  1324. }
  1325. catch (OperationCanceledException)
  1326. {
  1327. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1328. throw;
  1329. }
  1330. catch (Exception ex)
  1331. {
  1332. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1333. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1334. return false;
  1335. }
  1336. }
  1337. public string FriendlyName =>
  1338. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1339. ? Environment.MachineName
  1340. : ServerConfigurationManager.Configuration.ServerName;
  1341. public int HttpPort { get; private set; }
  1342. public int HttpsPort { get; private set; }
  1343. /// <summary>
  1344. /// Shuts down.
  1345. /// </summary>
  1346. public async Task Shutdown()
  1347. {
  1348. if (IsShuttingDown)
  1349. {
  1350. return;
  1351. }
  1352. IsShuttingDown = true;
  1353. try
  1354. {
  1355. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1356. }
  1357. catch (Exception ex)
  1358. {
  1359. Logger.LogError(ex, "Error sending server shutdown notification");
  1360. }
  1361. ShutdownInternal();
  1362. }
  1363. protected abstract void ShutdownInternal();
  1364. public event EventHandler HasUpdateAvailableChanged;
  1365. private bool _hasUpdateAvailable;
  1366. public bool HasUpdateAvailable
  1367. {
  1368. get => _hasUpdateAvailable;
  1369. set
  1370. {
  1371. var fireEvent = value && !_hasUpdateAvailable;
  1372. _hasUpdateAvailable = value;
  1373. if (fireEvent)
  1374. {
  1375. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1376. }
  1377. }
  1378. }
  1379. /// <summary>
  1380. /// Removes the plugin.
  1381. /// </summary>
  1382. /// <param name="plugin">The plugin.</param>
  1383. public void RemovePlugin(IPlugin plugin)
  1384. {
  1385. var list = Plugins.ToList();
  1386. list.Remove(plugin);
  1387. Plugins = list.ToArray();
  1388. }
  1389. /// <summary>
  1390. /// This returns localhost in the case of no external dns, and the hostname if the
  1391. /// dns is prefixed with a valid Uri prefix.
  1392. /// </summary>
  1393. /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
  1394. /// <returns>The hostname in <paramref name="externalDns"/></returns>
  1395. private static string GetHostnameFromExternalDns(string externalDns)
  1396. {
  1397. if (string.IsNullOrEmpty(externalDns))
  1398. {
  1399. return "localhost";
  1400. }
  1401. try
  1402. {
  1403. return new Uri(externalDns).Host;
  1404. }
  1405. catch
  1406. {
  1407. return externalDns;
  1408. }
  1409. }
  1410. public virtual void LaunchUrl(string url)
  1411. {
  1412. if (!CanLaunchWebBrowser)
  1413. {
  1414. throw new NotSupportedException();
  1415. }
  1416. var process = ProcessFactory.Create(new ProcessOptions
  1417. {
  1418. FileName = url,
  1419. EnableRaisingEvents = true,
  1420. UseShellExecute = true,
  1421. ErrorDialog = false
  1422. });
  1423. process.Exited += ProcessExited;
  1424. try
  1425. {
  1426. process.Start();
  1427. }
  1428. catch (Exception ex)
  1429. {
  1430. Logger.LogError(ex, "Error launching url: {url}", url);
  1431. throw;
  1432. }
  1433. }
  1434. private static void ProcessExited(object sender, EventArgs e)
  1435. {
  1436. ((IProcess)sender).Dispose();
  1437. }
  1438. public virtual void EnableLoopback(string appName)
  1439. {
  1440. }
  1441. private bool _disposed = false;
  1442. /// <summary>
  1443. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1444. /// </summary>
  1445. public void Dispose()
  1446. {
  1447. Dispose(true);
  1448. GC.SuppressFinalize(this);
  1449. }
  1450. /// <summary>
  1451. /// Releases unmanaged and - optionally - managed resources.
  1452. /// </summary>
  1453. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1454. protected virtual void Dispose(bool dispose)
  1455. {
  1456. if (_disposed)
  1457. {
  1458. return;
  1459. }
  1460. if (dispose)
  1461. {
  1462. var type = GetType();
  1463. Logger.LogInformation("Disposing {Type}", type.Name);
  1464. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1465. _disposableParts.Clear();
  1466. foreach (var part in parts)
  1467. {
  1468. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1469. try
  1470. {
  1471. part.Dispose();
  1472. }
  1473. catch (Exception ex)
  1474. {
  1475. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1476. }
  1477. }
  1478. _userRepository?.Dispose();
  1479. _displayPreferencesRepository.Dispose();
  1480. }
  1481. _userRepository = null;
  1482. _displayPreferencesRepository = null;
  1483. _disposed = true;
  1484. }
  1485. }
  1486. internal class CertificateInfo
  1487. {
  1488. public string Path { get; set; }
  1489. public string Password { get; set; }
  1490. }
  1491. }