ApplicationHost.cs 66 KB

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