ApplicationHost.cs 67 KB

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