ApplicationHost.cs 67 KB

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