ApplicationHost.cs 60 KB

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