ApplicationHost.cs 65 KB

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