ApplicationHost.cs 60 KB

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