ApplicationHost.cs 64 KB

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