ApplicationHost.cs 62 KB

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