ApplicationHost.cs 65 KB

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