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