ApplicationHost.cs 61 KB

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