ApplicationHost.cs 66 KB

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