ApplicationHost.cs 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  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. // TODO: Support for injecting ILogger should be deprecated in favour of ILogger<T> and this removed
  546. serviceCollection.AddSingleton<ILogger>(Logger);
  547. serviceCollection.AddSingleton(FileSystemManager);
  548. serviceCollection.AddSingleton<TvDbClientManager>();
  549. HttpClient = new HttpClientManager.HttpClientManager(
  550. ApplicationPaths,
  551. LoggerFactory.CreateLogger<HttpClientManager.HttpClientManager>(),
  552. FileSystemManager,
  553. () => ApplicationUserAgent);
  554. serviceCollection.AddSingleton(HttpClient);
  555. serviceCollection.AddSingleton(NetworkManager);
  556. IsoManager = new IsoManager();
  557. serviceCollection.AddSingleton(IsoManager);
  558. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory, FileSystemManager);
  559. serviceCollection.AddSingleton(TaskManager);
  560. serviceCollection.AddSingleton(XmlSerializer);
  561. ProcessFactory = new ProcessFactory();
  562. serviceCollection.AddSingleton(ProcessFactory);
  563. serviceCollection.AddSingleton(typeof(IStreamHelper), typeof(StreamHelper));
  564. var cryptoProvider = new CryptographyProvider();
  565. serviceCollection.AddSingleton<ICryptoProvider>(cryptoProvider);
  566. SocketFactory = new SocketFactory();
  567. serviceCollection.AddSingleton(SocketFactory);
  568. serviceCollection.AddSingleton(typeof(IInstallationManager), typeof(InstallationManager));
  569. serviceCollection.AddSingleton(typeof(IZipClient), typeof(ZipClient));
  570. serviceCollection.AddSingleton(typeof(IHttpResultFactory), typeof(HttpResultFactory));
  571. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  572. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  573. serviceCollection.AddSingleton(ServerConfigurationManager);
  574. LocalizationManager = new LocalizationManager(ServerConfigurationManager, JsonSerializer, LoggerFactory.CreateLogger<LocalizationManager>());
  575. await LocalizationManager.LoadAll().ConfigureAwait(false);
  576. serviceCollection.AddSingleton<ILocalizationManager>(LocalizationManager);
  577. serviceCollection.AddSingleton<IBlurayExaminer>(new BdInfoExaminer(FileSystemManager));
  578. UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
  579. serviceCollection.AddSingleton(UserDataManager);
  580. _displayPreferencesRepository = new SqliteDisplayPreferencesRepository(
  581. LoggerFactory.CreateLogger<SqliteDisplayPreferencesRepository>(),
  582. ApplicationPaths,
  583. FileSystemManager);
  584. serviceCollection.AddSingleton<IDisplayPreferencesRepository>(_displayPreferencesRepository);
  585. ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, LoggerFactory.CreateLogger<SqliteItemRepository>(), LocalizationManager);
  586. serviceCollection.AddSingleton<IItemRepository>(ItemRepository);
  587. AuthenticationRepository = GetAuthenticationRepository();
  588. serviceCollection.AddSingleton(AuthenticationRepository);
  589. _userRepository = GetUserRepository();
  590. UserManager = new UserManager(
  591. LoggerFactory.CreateLogger<UserManager>(),
  592. _userRepository,
  593. XmlSerializer,
  594. NetworkManager,
  595. () => ImageProcessor,
  596. () => DtoService,
  597. this,
  598. JsonSerializer,
  599. FileSystemManager,
  600. cryptoProvider);
  601. serviceCollection.AddSingleton(UserManager);
  602. MediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  603. LoggerFactory.CreateLogger<MediaBrowser.MediaEncoding.Encoder.MediaEncoder>(),
  604. ServerConfigurationManager,
  605. FileSystemManager,
  606. ProcessFactory,
  607. LocalizationManager,
  608. () => SubtitleEncoder,
  609. _configuration,
  610. StartupOptions.FFmpegPath);
  611. serviceCollection.AddSingleton(MediaEncoder);
  612. LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager, MediaEncoder);
  613. serviceCollection.AddSingleton(LibraryManager);
  614. var musicManager = new MusicManager(LibraryManager);
  615. serviceCollection.AddSingleton<IMusicManager>(musicManager);
  616. LibraryMonitor = new LibraryMonitor(LoggerFactory, LibraryManager, ServerConfigurationManager, FileSystemManager);
  617. serviceCollection.AddSingleton(LibraryMonitor);
  618. serviceCollection.AddSingleton<ISearchEngine>(new SearchEngine(LoggerFactory, LibraryManager, UserManager));
  619. CertificateInfo = GetCertificateInfo(true);
  620. Certificate = GetCertificate(CertificateInfo);
  621. HttpServer = new HttpListenerHost(
  622. this,
  623. LoggerFactory.CreateLogger<HttpListenerHost>(),
  624. ServerConfigurationManager,
  625. _configuration,
  626. NetworkManager,
  627. JsonSerializer,
  628. XmlSerializer,
  629. CreateHttpListener())
  630. {
  631. GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading")
  632. };
  633. serviceCollection.AddSingleton(HttpServer);
  634. ImageProcessor = new ImageProcessor(LoggerFactory.CreateLogger<ImageProcessor>(), ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
  635. serviceCollection.AddSingleton(ImageProcessor);
  636. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  637. serviceCollection.AddSingleton(TVSeriesManager);
  638. DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager);
  639. serviceCollection.AddSingleton(DeviceManager);
  640. MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, () => MediaEncoder);
  641. serviceCollection.AddSingleton(MediaSourceManager);
  642. SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
  643. serviceCollection.AddSingleton(SubtitleManager);
  644. ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
  645. serviceCollection.AddSingleton(ProviderManager);
  646. DtoService = new DtoService(LoggerFactory, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ProviderManager, this, () => MediaSourceManager, () => LiveTvManager);
  647. serviceCollection.AddSingleton(DtoService);
  648. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, ProviderManager);
  649. serviceCollection.AddSingleton(ChannelManager);
  650. SessionManager = new SessionManager(
  651. LoggerFactory.CreateLogger<SessionManager>(),
  652. UserDataManager,
  653. LibraryManager,
  654. UserManager,
  655. musicManager,
  656. DtoService,
  657. ImageProcessor,
  658. this,
  659. AuthenticationRepository,
  660. DeviceManager,
  661. MediaSourceManager);
  662. serviceCollection.AddSingleton(SessionManager);
  663. serviceCollection.AddSingleton<IDlnaManager>(
  664. new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory, JsonSerializer, this));
  665. CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager);
  666. serviceCollection.AddSingleton(CollectionManager);
  667. serviceCollection.AddSingleton(typeof(IPlaylistManager), typeof(PlaylistManager));
  668. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, FileSystemManager, () => ChannelManager);
  669. serviceCollection.AddSingleton(LiveTvManager);
  670. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  671. serviceCollection.AddSingleton(UserViewManager);
  672. NotificationManager = new NotificationManager(
  673. LoggerFactory.CreateLogger<NotificationManager>(),
  674. UserManager,
  675. ServerConfigurationManager);
  676. serviceCollection.AddSingleton(NotificationManager);
  677. serviceCollection.AddSingleton<IDeviceDiscovery>(new DeviceDiscovery(ServerConfigurationManager));
  678. ChapterManager = new ChapterManager(LibraryManager, LoggerFactory, ServerConfigurationManager, ItemRepository);
  679. serviceCollection.AddSingleton(ChapterManager);
  680. EncodingManager = new MediaEncoder.EncodingManager(FileSystemManager, LoggerFactory, MediaEncoder, ChapterManager, LibraryManager);
  681. serviceCollection.AddSingleton(EncodingManager);
  682. var activityLogRepo = GetActivityLogRepository();
  683. serviceCollection.AddSingleton(activityLogRepo);
  684. serviceCollection.AddSingleton<IActivityManager>(new ActivityManager(LoggerFactory, activityLogRepo, UserManager));
  685. var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
  686. serviceCollection.AddSingleton<IAuthorizationContext>(authContext);
  687. serviceCollection.AddSingleton<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  688. AuthService = new AuthService(LoggerFactory.CreateLogger<AuthService>(), authContext, ServerConfigurationManager, SessionManager, NetworkManager);
  689. serviceCollection.AddSingleton(AuthService);
  690. SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(
  691. LibraryManager,
  692. LoggerFactory.CreateLogger<MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>(),
  693. ApplicationPaths,
  694. FileSystemManager,
  695. MediaEncoder,
  696. HttpClient,
  697. MediaSourceManager,
  698. ProcessFactory);
  699. serviceCollection.AddSingleton(SubtitleEncoder);
  700. serviceCollection.AddSingleton(typeof(IResourceFileManager), typeof(ResourceFileManager));
  701. serviceCollection.AddSingleton<EncodingHelper>();
  702. serviceCollection.AddSingleton(typeof(IAttachmentExtractor), typeof(MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor));
  703. _displayPreferencesRepository.Initialize();
  704. var userDataRepo = new SqliteUserDataRepository(LoggerFactory.CreateLogger<SqliteUserDataRepository>(), ApplicationPaths);
  705. SetStaticProperties();
  706. ((UserManager)UserManager).Initialize();
  707. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  708. ItemRepository.Initialize(userDataRepo, UserManager);
  709. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  710. }
  711. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  712. {
  713. // Distinct these to prevent users from reporting problems that aren't actually problems
  714. var commandLineArgs = Environment
  715. .GetCommandLineArgs()
  716. .Distinct();
  717. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  718. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  719. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  720. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  721. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  722. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  723. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  724. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  725. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  726. }
  727. private X509Certificate2 GetCertificate(CertificateInfo info)
  728. {
  729. var certificateLocation = info?.Path;
  730. if (string.IsNullOrWhiteSpace(certificateLocation))
  731. {
  732. return null;
  733. }
  734. try
  735. {
  736. if (!File.Exists(certificateLocation))
  737. {
  738. return null;
  739. }
  740. // Don't use an empty string password
  741. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  742. var localCert = new X509Certificate2(certificateLocation, password);
  743. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  744. if (!localCert.HasPrivateKey)
  745. {
  746. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  747. return null;
  748. }
  749. return localCert;
  750. }
  751. catch (Exception ex)
  752. {
  753. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  754. return null;
  755. }
  756. }
  757. /// <summary>
  758. /// Gets the user repository.
  759. /// </summary>
  760. /// <returns><see cref="Task{SqliteUserRepository}" />.</returns>
  761. private SqliteUserRepository GetUserRepository()
  762. {
  763. var repo = new SqliteUserRepository(
  764. LoggerFactory.CreateLogger<SqliteUserRepository>(),
  765. ApplicationPaths);
  766. repo.Initialize();
  767. return repo;
  768. }
  769. private IAuthenticationRepository GetAuthenticationRepository()
  770. {
  771. var repo = new AuthenticationRepository(LoggerFactory, ServerConfigurationManager);
  772. repo.Initialize();
  773. return repo;
  774. }
  775. private IActivityRepository GetActivityLogRepository()
  776. {
  777. var repo = new ActivityRepository(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager);
  778. repo.Initialize();
  779. return repo;
  780. }
  781. /// <summary>
  782. /// Dirty hacks.
  783. /// </summary>
  784. private void SetStaticProperties()
  785. {
  786. ItemRepository.ImageProcessor = ImageProcessor;
  787. // For now there's no real way to inject these properly
  788. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  789. BaseItem.ConfigurationManager = ServerConfigurationManager;
  790. BaseItem.LibraryManager = LibraryManager;
  791. BaseItem.ProviderManager = ProviderManager;
  792. BaseItem.LocalizationManager = LocalizationManager;
  793. BaseItem.ItemRepository = ItemRepository;
  794. User.UserManager = UserManager;
  795. BaseItem.FileSystem = FileSystemManager;
  796. BaseItem.UserDataManager = UserDataManager;
  797. BaseItem.ChannelManager = ChannelManager;
  798. Video.LiveTvManager = LiveTvManager;
  799. Folder.UserViewManager = UserViewManager;
  800. UserView.TVSeriesManager = TVSeriesManager;
  801. UserView.CollectionManager = CollectionManager;
  802. BaseItem.MediaSourceManager = MediaSourceManager;
  803. CollectionFolder.XmlSerializer = XmlSerializer;
  804. CollectionFolder.JsonSerializer = JsonSerializer;
  805. CollectionFolder.ApplicationHost = this;
  806. AuthenticatedAttribute.AuthService = AuthService;
  807. }
  808. /// <summary>
  809. /// Finds the parts.
  810. /// </summary>
  811. public void FindParts()
  812. {
  813. InstallationManager = ServiceProvider.GetService<IInstallationManager>();
  814. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  815. {
  816. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  817. ConfigurationManager.SaveConfiguration();
  818. }
  819. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  820. _plugins = GetExports<IPlugin>()
  821. .Select(LoadPlugin)
  822. .Where(i => i != null)
  823. .ToArray();
  824. HttpServer.Init(GetExports<IService>(false), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  825. LibraryManager.AddParts(
  826. GetExports<IResolverIgnoreRule>(),
  827. GetExports<IItemResolver>(),
  828. GetExports<IIntroProvider>(),
  829. GetExports<IBaseItemComparer>(),
  830. GetExports<ILibraryPostScanTask>());
  831. ProviderManager.AddParts(
  832. GetExports<IImageProvider>(),
  833. GetExports<IMetadataService>(),
  834. GetExports<IMetadataProvider>(),
  835. GetExports<IMetadataSaver>(),
  836. GetExports<IExternalId>());
  837. LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  838. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  839. ChannelManager.AddParts(GetExports<IChannel>());
  840. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  841. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  842. UserManager.AddParts(GetExports<IAuthenticationProvider>(), GetExports<IPasswordResetProvider>());
  843. IsoManager.AddParts(GetExports<IIsoMounter>());
  844. }
  845. private IPlugin LoadPlugin(IPlugin plugin)
  846. {
  847. try
  848. {
  849. if (plugin is IPluginAssembly assemblyPlugin)
  850. {
  851. var assembly = plugin.GetType().Assembly;
  852. var assemblyName = assembly.GetName();
  853. var assemblyFilePath = assembly.Location;
  854. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  855. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  856. try
  857. {
  858. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  859. if (idAttributes.Length > 0)
  860. {
  861. var attribute = (GuidAttribute)idAttributes[0];
  862. var assemblyId = new Guid(attribute.Value);
  863. assemblyPlugin.SetId(assemblyId);
  864. }
  865. }
  866. catch (Exception ex)
  867. {
  868. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  869. }
  870. }
  871. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  872. {
  873. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  874. }
  875. }
  876. catch (Exception ex)
  877. {
  878. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  879. return null;
  880. }
  881. return plugin;
  882. }
  883. /// <summary>
  884. /// Discovers the types.
  885. /// </summary>
  886. protected void DiscoverTypes()
  887. {
  888. Logger.LogInformation("Loading assemblies");
  889. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  890. }
  891. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  892. {
  893. foreach (var ass in assemblies)
  894. {
  895. Type[] exportedTypes;
  896. try
  897. {
  898. exportedTypes = ass.GetExportedTypes();
  899. }
  900. catch (FileNotFoundException ex)
  901. {
  902. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  903. continue;
  904. }
  905. foreach (Type type in exportedTypes)
  906. {
  907. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  908. {
  909. yield return type;
  910. }
  911. }
  912. }
  913. }
  914. private CertificateInfo CertificateInfo { get; set; }
  915. public X509Certificate2 Certificate { get; private set; }
  916. private IEnumerable<string> GetUrlPrefixes()
  917. {
  918. var hosts = new[] { "+" };
  919. return hosts.SelectMany(i =>
  920. {
  921. var prefixes = new List<string>
  922. {
  923. "http://" + i + ":" + HttpPort + "/"
  924. };
  925. if (CertificateInfo != null)
  926. {
  927. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  928. }
  929. return prefixes;
  930. });
  931. }
  932. protected IHttpListener CreateHttpListener() => new WebSocketSharpListener(Logger);
  933. private CertificateInfo GetCertificateInfo(bool generateCertificate)
  934. {
  935. // Custom cert
  936. return new CertificateInfo
  937. {
  938. Path = ServerConfigurationManager.Configuration.CertificatePath,
  939. Password = ServerConfigurationManager.Configuration.CertificatePassword
  940. };
  941. }
  942. /// <summary>
  943. /// Called when [configuration updated].
  944. /// </summary>
  945. /// <param name="sender">The sender.</param>
  946. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  947. protected void OnConfigurationUpdated(object sender, EventArgs e)
  948. {
  949. var requiresRestart = false;
  950. // Don't do anything if these haven't been set yet
  951. if (HttpPort != 0 && HttpsPort != 0)
  952. {
  953. // Need to restart if ports have changed
  954. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  955. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  956. {
  957. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  958. {
  959. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  960. ServerConfigurationManager.SaveConfiguration();
  961. requiresRestart = true;
  962. }
  963. }
  964. }
  965. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  966. {
  967. requiresRestart = true;
  968. }
  969. var currentCertPath = CertificateInfo?.Path;
  970. var newCertInfo = GetCertificateInfo(false);
  971. var newCertPath = newCertInfo?.Path;
  972. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  973. {
  974. requiresRestart = true;
  975. }
  976. if (requiresRestart)
  977. {
  978. Logger.LogInformation("App needs to be restarted due to configuration change.");
  979. NotifyPendingRestart();
  980. }
  981. }
  982. /// <summary>
  983. /// Notifies that the kernel that a change has been made that requires a restart
  984. /// </summary>
  985. public void NotifyPendingRestart()
  986. {
  987. Logger.LogInformation("App needs to be restarted.");
  988. var changed = !HasPendingRestart;
  989. HasPendingRestart = true;
  990. if (changed)
  991. {
  992. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  993. }
  994. }
  995. /// <summary>
  996. /// Restarts this instance.
  997. /// </summary>
  998. public void Restart()
  999. {
  1000. if (!CanSelfRestart)
  1001. {
  1002. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  1003. }
  1004. if (IsShuttingDown)
  1005. {
  1006. return;
  1007. }
  1008. IsShuttingDown = true;
  1009. Task.Run(async () =>
  1010. {
  1011. try
  1012. {
  1013. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  1014. }
  1015. catch (Exception ex)
  1016. {
  1017. Logger.LogError(ex, "Error sending server restart notification");
  1018. }
  1019. Logger.LogInformation("Calling RestartInternal");
  1020. RestartInternal();
  1021. });
  1022. }
  1023. protected abstract void RestartInternal();
  1024. /// <summary>
  1025. /// Gets the composable part assemblies.
  1026. /// </summary>
  1027. /// <returns>IEnumerable{Assembly}.</returns>
  1028. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  1029. {
  1030. if (Directory.Exists(ApplicationPaths.PluginsPath))
  1031. {
  1032. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  1033. {
  1034. Assembly plugAss;
  1035. try
  1036. {
  1037. plugAss = Assembly.LoadFrom(file);
  1038. }
  1039. catch (FileLoadException ex)
  1040. {
  1041. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  1042. continue;
  1043. }
  1044. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  1045. yield return plugAss;
  1046. }
  1047. }
  1048. // Include composable parts in the Api assembly
  1049. yield return typeof(ApiEntryPoint).Assembly;
  1050. // Include composable parts in the Dashboard assembly
  1051. yield return typeof(DashboardService).Assembly;
  1052. // Include composable parts in the Model assembly
  1053. yield return typeof(SystemInfo).Assembly;
  1054. // Include composable parts in the Common assembly
  1055. yield return typeof(IApplicationHost).Assembly;
  1056. // Include composable parts in the Controller assembly
  1057. yield return typeof(IServerApplicationHost).Assembly;
  1058. // Include composable parts in the Providers assembly
  1059. yield return typeof(ProviderUtils).Assembly;
  1060. // Include composable parts in the Photos assembly
  1061. yield return typeof(PhotoProvider).Assembly;
  1062. // Emby.Server implementations
  1063. yield return typeof(InstallationManager).Assembly;
  1064. // MediaEncoding
  1065. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  1066. // Dlna
  1067. yield return typeof(DlnaEntryPoint).Assembly;
  1068. // Local metadata
  1069. yield return typeof(BoxSetXmlSaver).Assembly;
  1070. // Notifications
  1071. yield return typeof(NotificationManager).Assembly;
  1072. // Xbmc
  1073. yield return typeof(ArtistNfoProvider).Assembly;
  1074. foreach (var i in GetAssembliesWithPartsInternal())
  1075. {
  1076. yield return i;
  1077. }
  1078. }
  1079. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  1080. /// <summary>
  1081. /// Gets the system status.
  1082. /// </summary>
  1083. /// <param name="cancellationToken">The cancellation token.</param>
  1084. /// <returns>SystemInfo.</returns>
  1085. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  1086. {
  1087. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1088. var transcodingTempPath = ConfigurationManager.GetTranscodePath();
  1089. return new SystemInfo
  1090. {
  1091. HasPendingRestart = HasPendingRestart,
  1092. IsShuttingDown = IsShuttingDown,
  1093. Version = ApplicationVersionString,
  1094. WebSocketPortNumber = HttpPort,
  1095. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  1096. Id = SystemId,
  1097. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1098. WebPath = ApplicationPaths.WebPath,
  1099. LogPath = ApplicationPaths.LogDirectoryPath,
  1100. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  1101. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1102. CachePath = ApplicationPaths.CachePath,
  1103. HttpServerPortNumber = HttpPort,
  1104. SupportsHttps = SupportsHttps,
  1105. HttpsPortNumber = HttpsPort,
  1106. OperatingSystem = OperatingSystem.Id.ToString(),
  1107. OperatingSystemDisplayName = OperatingSystem.Name,
  1108. CanSelfRestart = CanSelfRestart,
  1109. CanLaunchWebBrowser = CanLaunchWebBrowser,
  1110. HasUpdateAvailable = HasUpdateAvailable,
  1111. TranscodingTempPath = transcodingTempPath,
  1112. ServerName = FriendlyName,
  1113. LocalAddress = localAddress,
  1114. SupportsLibraryMonitor = true,
  1115. EncoderLocation = MediaEncoder.EncoderLocation,
  1116. SystemArchitecture = RuntimeInformation.OSArchitecture,
  1117. SystemUpdateLevel = SystemUpdateLevel,
  1118. PackageName = StartupOptions.PackageName
  1119. };
  1120. }
  1121. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  1122. => NetworkManager.GetMacAddresses()
  1123. .Select(i => new WakeOnLanInfo(i))
  1124. .ToList();
  1125. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1126. {
  1127. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1128. return new PublicSystemInfo
  1129. {
  1130. Version = ApplicationVersionString,
  1131. ProductName = ApplicationProductName,
  1132. Id = SystemId,
  1133. OperatingSystem = OperatingSystem.Id.ToString(),
  1134. ServerName = FriendlyName,
  1135. LocalAddress = localAddress
  1136. };
  1137. }
  1138. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1139. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1140. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken, bool forceHttp = false)
  1141. {
  1142. try
  1143. {
  1144. // Return the first matched address, if found, or the first known local address
  1145. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1146. foreach (var address in addresses)
  1147. {
  1148. return GetLocalApiUrl(address, forceHttp);
  1149. }
  1150. return null;
  1151. }
  1152. catch (Exception ex)
  1153. {
  1154. Logger.LogError(ex, "Error getting local Ip address information");
  1155. }
  1156. return null;
  1157. }
  1158. /// <summary>
  1159. /// Removes the scope id from IPv6 addresses.
  1160. /// </summary>
  1161. /// <param name="address">The IPv6 address.</param>
  1162. /// <returns>The IPv6 address without the scope id.</returns>
  1163. private ReadOnlySpan<char> RemoveScopeId(ReadOnlySpan<char> address)
  1164. {
  1165. var index = address.IndexOf('%');
  1166. if (index == -1)
  1167. {
  1168. return address;
  1169. }
  1170. return address.Slice(0, index);
  1171. }
  1172. /// <inheritdoc />
  1173. public string GetLocalApiUrl(IPAddress ipAddress, bool forceHttp = false)
  1174. {
  1175. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1176. {
  1177. var str = RemoveScopeId(ipAddress.ToString());
  1178. Span<char> span = new char[str.Length + 2];
  1179. span[0] = '[';
  1180. str.CopyTo(span.Slice(1));
  1181. span[^1] = ']';
  1182. return GetLocalApiUrl(span, forceHttp);
  1183. }
  1184. return GetLocalApiUrl(ipAddress.ToString(), forceHttp);
  1185. }
  1186. /// <inheritdoc />
  1187. public string GetLocalApiUrl(ReadOnlySpan<char> host, bool forceHttp = false)
  1188. {
  1189. var url = new StringBuilder(64);
  1190. bool useHttps = EnableHttps && !forceHttp;
  1191. url.Append(useHttps ? "https://" : "http://")
  1192. .Append(host)
  1193. .Append(':')
  1194. .Append(useHttps ? HttpsPort : HttpPort);
  1195. string baseUrl = ServerConfigurationManager.Configuration.BaseUrl;
  1196. if (baseUrl.Length != 0)
  1197. {
  1198. url.Append(baseUrl);
  1199. }
  1200. return url.ToString();
  1201. }
  1202. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1203. {
  1204. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1205. }
  1206. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1207. {
  1208. var addresses = ServerConfigurationManager
  1209. .Configuration
  1210. .LocalNetworkAddresses
  1211. .Select(NormalizeConfiguredLocalAddress)
  1212. .Where(i => i != null)
  1213. .ToList();
  1214. if (addresses.Count == 0)
  1215. {
  1216. addresses.AddRange(NetworkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1217. }
  1218. var resultList = new List<IPAddress>();
  1219. foreach (var address in addresses)
  1220. {
  1221. if (!allowLoopback)
  1222. {
  1223. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1224. {
  1225. continue;
  1226. }
  1227. }
  1228. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1229. if (valid)
  1230. {
  1231. resultList.Add(address);
  1232. if (limit > 0 && resultList.Count >= limit)
  1233. {
  1234. return resultList;
  1235. }
  1236. }
  1237. }
  1238. return resultList;
  1239. }
  1240. public IPAddress NormalizeConfiguredLocalAddress(string address)
  1241. {
  1242. var index = address.Trim('/').IndexOf('/');
  1243. if (index != -1)
  1244. {
  1245. address = address.Substring(index + 1);
  1246. }
  1247. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1248. {
  1249. return result;
  1250. }
  1251. return null;
  1252. }
  1253. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1254. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1255. {
  1256. if (address.Equals(IPAddress.Loopback)
  1257. || address.Equals(IPAddress.IPv6Loopback))
  1258. {
  1259. return true;
  1260. }
  1261. var apiUrl = GetLocalApiUrl(address);
  1262. apiUrl += "/system/ping";
  1263. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1264. {
  1265. return cachedResult;
  1266. }
  1267. try
  1268. {
  1269. using (var response = await HttpClient.SendAsync(
  1270. new HttpRequestOptions
  1271. {
  1272. Url = apiUrl,
  1273. LogErrorResponseBody = false,
  1274. BufferContent = false,
  1275. CancellationToken = cancellationToken
  1276. }, HttpMethod.Post).ConfigureAwait(false))
  1277. {
  1278. using (var reader = new StreamReader(response.Content))
  1279. {
  1280. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1281. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1282. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1283. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1284. return valid;
  1285. }
  1286. }
  1287. }
  1288. catch (OperationCanceledException)
  1289. {
  1290. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1291. throw;
  1292. }
  1293. catch (Exception ex)
  1294. {
  1295. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1296. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1297. return false;
  1298. }
  1299. }
  1300. public string FriendlyName =>
  1301. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1302. ? Environment.MachineName
  1303. : ServerConfigurationManager.Configuration.ServerName;
  1304. /// <summary>
  1305. /// Shuts down.
  1306. /// </summary>
  1307. public async Task Shutdown()
  1308. {
  1309. if (IsShuttingDown)
  1310. {
  1311. return;
  1312. }
  1313. IsShuttingDown = true;
  1314. try
  1315. {
  1316. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1317. }
  1318. catch (Exception ex)
  1319. {
  1320. Logger.LogError(ex, "Error sending server shutdown notification");
  1321. }
  1322. ShutdownInternal();
  1323. }
  1324. protected abstract void ShutdownInternal();
  1325. public event EventHandler HasUpdateAvailableChanged;
  1326. private bool _hasUpdateAvailable;
  1327. public bool HasUpdateAvailable
  1328. {
  1329. get => _hasUpdateAvailable;
  1330. set
  1331. {
  1332. var fireEvent = value && !_hasUpdateAvailable;
  1333. _hasUpdateAvailable = value;
  1334. if (fireEvent)
  1335. {
  1336. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1337. }
  1338. }
  1339. }
  1340. /// <summary>
  1341. /// Removes the plugin.
  1342. /// </summary>
  1343. /// <param name="plugin">The plugin.</param>
  1344. public void RemovePlugin(IPlugin plugin)
  1345. {
  1346. var list = _plugins.ToList();
  1347. list.Remove(plugin);
  1348. _plugins = list.ToArray();
  1349. }
  1350. public virtual void LaunchUrl(string url)
  1351. {
  1352. if (!CanLaunchWebBrowser)
  1353. {
  1354. throw new NotSupportedException();
  1355. }
  1356. var process = ProcessFactory.Create(new ProcessOptions
  1357. {
  1358. FileName = url,
  1359. EnableRaisingEvents = true,
  1360. UseShellExecute = true,
  1361. ErrorDialog = false
  1362. });
  1363. process.Exited += ProcessExited;
  1364. try
  1365. {
  1366. process.Start();
  1367. }
  1368. catch (Exception ex)
  1369. {
  1370. Logger.LogError(ex, "Error launching url: {url}", url);
  1371. throw;
  1372. }
  1373. }
  1374. private static void ProcessExited(object sender, EventArgs e)
  1375. {
  1376. ((IProcess)sender).Dispose();
  1377. }
  1378. public virtual void EnableLoopback(string appName)
  1379. {
  1380. }
  1381. private bool _disposed = false;
  1382. /// <summary>
  1383. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1384. /// </summary>
  1385. public void Dispose()
  1386. {
  1387. Dispose(true);
  1388. GC.SuppressFinalize(this);
  1389. }
  1390. /// <summary>
  1391. /// Releases unmanaged and - optionally - managed resources.
  1392. /// </summary>
  1393. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1394. protected virtual void Dispose(bool dispose)
  1395. {
  1396. if (_disposed)
  1397. {
  1398. return;
  1399. }
  1400. if (dispose)
  1401. {
  1402. var type = GetType();
  1403. Logger.LogInformation("Disposing {Type}", type.Name);
  1404. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1405. _disposableParts.Clear();
  1406. foreach (var part in parts)
  1407. {
  1408. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1409. try
  1410. {
  1411. part.Dispose();
  1412. }
  1413. catch (Exception ex)
  1414. {
  1415. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1416. }
  1417. }
  1418. _userRepository?.Dispose();
  1419. _displayPreferencesRepository?.Dispose();
  1420. }
  1421. _userRepository = null;
  1422. _displayPreferencesRepository = null;
  1423. _disposed = true;
  1424. }
  1425. }
  1426. internal class CertificateInfo
  1427. {
  1428. public string Path { get; set; }
  1429. public string Password { get; set; }
  1430. }
  1431. }