ApplicationHost.cs 66 KB

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