2
0

ApplicationHost.cs 63 KB

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