ApplicationHost.cs 63 KB

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