ApplicationHost.cs 62 KB

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