2
0

ApplicationHost.cs 59 KB

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