ApplicationHost.cs 65 KB

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