ApplicationHost.cs 66 KB

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