ApplicationHost.cs 64 KB

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