ApplicationHost.cs 65 KB

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