2
0

ApplicationHost.cs 64 KB

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