ApplicationHost.cs 67 KB

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