ApplicationHost.cs 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789
  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.Dto;
  33. using Emby.Server.Implementations.HttpServer;
  34. using Emby.Server.Implementations.HttpServer.Security;
  35. using Emby.Server.Implementations.IO;
  36. using Emby.Server.Implementations.Library;
  37. using Emby.Server.Implementations.LiveTv;
  38. using Emby.Server.Implementations.Localization;
  39. using Emby.Server.Implementations.Net;
  40. using Emby.Server.Implementations.Playlists;
  41. using Emby.Server.Implementations.ScheduledTasks;
  42. using Emby.Server.Implementations.Security;
  43. using Emby.Server.Implementations.Serialization;
  44. using Emby.Server.Implementations.Services;
  45. using Emby.Server.Implementations.Session;
  46. using Emby.Server.Implementations.SocketSharp;
  47. using Emby.Server.Implementations.TV;
  48. using Emby.Server.Implementations.Updates;
  49. using MediaBrowser.Api;
  50. using MediaBrowser.Common;
  51. using MediaBrowser.Common.Configuration;
  52. using MediaBrowser.Common.Events;
  53. using MediaBrowser.Common.Net;
  54. using MediaBrowser.Common.Plugins;
  55. using MediaBrowser.Common.Updates;
  56. using MediaBrowser.Controller;
  57. using MediaBrowser.Controller.Authentication;
  58. using MediaBrowser.Controller.Channels;
  59. using MediaBrowser.Controller.Chapters;
  60. using MediaBrowser.Controller.Collections;
  61. using MediaBrowser.Controller.Configuration;
  62. using MediaBrowser.Controller.Devices;
  63. using MediaBrowser.Controller.Dlna;
  64. using MediaBrowser.Controller.Drawing;
  65. using MediaBrowser.Controller.Dto;
  66. using MediaBrowser.Controller.Entities;
  67. using MediaBrowser.Controller.Library;
  68. using MediaBrowser.Controller.LiveTv;
  69. using MediaBrowser.Controller.MediaEncoding;
  70. using MediaBrowser.Controller.Net;
  71. using MediaBrowser.Controller.Notifications;
  72. using MediaBrowser.Controller.Persistence;
  73. using MediaBrowser.Controller.Playlists;
  74. using MediaBrowser.Controller.Plugins;
  75. using MediaBrowser.Controller.Providers;
  76. using MediaBrowser.Controller.Resolvers;
  77. using MediaBrowser.Controller.Security;
  78. using MediaBrowser.Controller.Session;
  79. using MediaBrowser.Controller.Sorting;
  80. using MediaBrowser.Controller.Subtitles;
  81. using MediaBrowser.Controller.TV;
  82. using MediaBrowser.LocalMetadata.Savers;
  83. using MediaBrowser.MediaEncoding.BdInfo;
  84. using MediaBrowser.Model.Activity;
  85. using MediaBrowser.Model.Configuration;
  86. using MediaBrowser.Model.Cryptography;
  87. using MediaBrowser.Model.Dlna;
  88. using MediaBrowser.Model.Events;
  89. using MediaBrowser.Model.Globalization;
  90. using MediaBrowser.Model.IO;
  91. using MediaBrowser.Model.MediaInfo;
  92. using MediaBrowser.Model.Net;
  93. using MediaBrowser.Model.Serialization;
  94. using MediaBrowser.Model.Services;
  95. using MediaBrowser.Model.System;
  96. using MediaBrowser.Model.Tasks;
  97. using MediaBrowser.Model.Updates;
  98. using MediaBrowser.Providers.Chapters;
  99. using MediaBrowser.Providers.Manager;
  100. using MediaBrowser.Providers.Plugins.TheTvdb;
  101. using MediaBrowser.Providers.Subtitles;
  102. using MediaBrowser.WebDashboard.Api;
  103. using MediaBrowser.XbmcMetadata.Providers;
  104. using Microsoft.AspNetCore.Http;
  105. using Microsoft.AspNetCore.Http.Extensions;
  106. using Microsoft.Extensions.Configuration;
  107. using Microsoft.Extensions.DependencyInjection;
  108. using Microsoft.Extensions.Logging;
  109. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  110. namespace Emby.Server.Implementations
  111. {
  112. /// <summary>
  113. /// Class CompositionRoot.
  114. /// </summary>
  115. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  116. {
  117. private SqliteUserRepository _userRepository;
  118. private SqliteDisplayPreferencesRepository _displayPreferencesRepository;
  119. /// <summary>
  120. /// Gets a value indicating whether this instance can self restart.
  121. /// </summary>
  122. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  123. public abstract bool CanSelfRestart { get; }
  124. public virtual bool CanLaunchWebBrowser
  125. {
  126. get
  127. {
  128. if (!Environment.UserInteractive)
  129. {
  130. return false;
  131. }
  132. if (StartupOptions.IsService)
  133. {
  134. return false;
  135. }
  136. if (OperatingSystem.Id == OperatingSystemId.Windows
  137. || OperatingSystem.Id == OperatingSystemId.Darwin)
  138. {
  139. return true;
  140. }
  141. return false;
  142. }
  143. }
  144. /// <summary>
  145. /// Occurs when [has pending restart changed].
  146. /// </summary>
  147. public event EventHandler HasPendingRestartChanged;
  148. /// <summary>
  149. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  150. /// </summary>
  151. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  152. public bool HasPendingRestart { get; private set; }
  153. /// <inheritdoc />
  154. public bool IsShuttingDown { get; private set; }
  155. /// <summary>
  156. /// Gets the logger.
  157. /// </summary>
  158. protected ILogger Logger { get; }
  159. private IPlugin[] _plugins;
  160. /// <summary>
  161. /// Gets the plugins.
  162. /// </summary>
  163. /// <value>The plugins.</value>
  164. public IReadOnlyList<IPlugin> Plugins => _plugins;
  165. /// <summary>
  166. /// Gets the logger factory.
  167. /// </summary>
  168. protected ILoggerFactory LoggerFactory { get; }
  169. /// <summary>
  170. /// Gets or sets the application paths.
  171. /// </summary>
  172. /// <value>The application paths.</value>
  173. protected ServerApplicationPaths ApplicationPaths { get; set; }
  174. /// <summary>
  175. /// Gets or sets all concrete types.
  176. /// </summary>
  177. /// <value>All concrete types.</value>
  178. private Type[] _allConcreteTypes;
  179. /// <summary>
  180. /// The disposable parts.
  181. /// </summary>
  182. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  183. /// <summary>
  184. /// Gets the configuration manager.
  185. /// </summary>
  186. /// <value>The configuration manager.</value>
  187. protected IConfigurationManager ConfigurationManager { get; set; }
  188. public IFileSystem FileSystemManager { get; set; }
  189. /// <inheritdoc />
  190. public PackageVersionClass SystemUpdateLevel
  191. {
  192. get
  193. {
  194. #if BETA
  195. return PackageVersionClass.Beta;
  196. #else
  197. return PackageVersionClass.Release;
  198. #endif
  199. }
  200. }
  201. /// <summary>
  202. /// Gets or sets the service provider.
  203. /// </summary>
  204. public IServiceProvider ServiceProvider { get; set; }
  205. /// <summary>
  206. /// Gets the http port for the webhost.
  207. /// </summary>
  208. public int HttpPort { get; private set; }
  209. /// <summary>
  210. /// Gets the https port for the webhost.
  211. /// </summary>
  212. public int HttpsPort { get; private set; }
  213. /// <summary>
  214. /// Gets the server configuration manager.
  215. /// </summary>
  216. /// <value>The server configuration manager.</value>
  217. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  218. /// <summary>
  219. /// Gets or sets the user manager.
  220. /// </summary>
  221. /// <value>The user manager.</value>
  222. public IUserManager UserManager { get; set; }
  223. /// <summary>
  224. /// Gets or sets the library manager.
  225. /// </summary>
  226. /// <value>The library manager.</value>
  227. internal ILibraryManager LibraryManager { get; set; }
  228. /// <summary>
  229. /// Gets or sets the directory watchers.
  230. /// </summary>
  231. /// <value>The directory watchers.</value>
  232. private ILibraryMonitor LibraryMonitor { get; set; }
  233. /// <summary>
  234. /// Gets or sets the provider manager.
  235. /// </summary>
  236. /// <value>The provider manager.</value>
  237. private IProviderManager ProviderManager { get; set; }
  238. /// <summary>
  239. /// Gets or sets the HTTP server.
  240. /// </summary>
  241. /// <value>The HTTP server.</value>
  242. private IHttpServer HttpServer { get; set; }
  243. private IDtoService DtoService { get; set; }
  244. public IImageProcessor ImageProcessor { get; set; }
  245. /// <summary>
  246. /// Gets or sets the media encoder.
  247. /// </summary>
  248. /// <value>The media encoder.</value>
  249. private IMediaEncoder MediaEncoder { get; set; }
  250. private ISubtitleEncoder SubtitleEncoder { get; set; }
  251. private ISessionManager SessionManager { get; set; }
  252. private ILiveTvManager LiveTvManager { get; set; }
  253. public LocalizationManager LocalizationManager { get; set; }
  254. private IEncodingManager EncodingManager { 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. protected IAuthService AuthService { get; private set; }
  277. public IStartupOptions StartupOptions { get; }
  278. internal IImageEncoder ImageEncoder { 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. serviceCollection.AddSingleton(typeof(IStreamHelper), typeof(StreamHelper));
  545. var cryptoProvider = new CryptographyProvider();
  546. serviceCollection.AddSingleton<ICryptoProvider>(cryptoProvider);
  547. SocketFactory = new SocketFactory();
  548. serviceCollection.AddSingleton(SocketFactory);
  549. serviceCollection.AddSingleton(typeof(IInstallationManager), typeof(InstallationManager));
  550. serviceCollection.AddSingleton(typeof(IZipClient), typeof(ZipClient));
  551. serviceCollection.AddSingleton(typeof(IHttpResultFactory), typeof(HttpResultFactory));
  552. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  553. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  554. serviceCollection.AddSingleton(ServerConfigurationManager);
  555. LocalizationManager = new LocalizationManager(ServerConfigurationManager, JsonSerializer, LoggerFactory.CreateLogger<LocalizationManager>());
  556. await LocalizationManager.LoadAll().ConfigureAwait(false);
  557. serviceCollection.AddSingleton<ILocalizationManager>(LocalizationManager);
  558. serviceCollection.AddSingleton<IBlurayExaminer>(new BdInfoExaminer(FileSystemManager));
  559. UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
  560. serviceCollection.AddSingleton(UserDataManager);
  561. _displayPreferencesRepository = new SqliteDisplayPreferencesRepository(
  562. LoggerFactory.CreateLogger<SqliteDisplayPreferencesRepository>(),
  563. ApplicationPaths,
  564. FileSystemManager);
  565. serviceCollection.AddSingleton<IDisplayPreferencesRepository>(_displayPreferencesRepository);
  566. ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, LoggerFactory.CreateLogger<SqliteItemRepository>(), LocalizationManager);
  567. serviceCollection.AddSingleton<IItemRepository>(ItemRepository);
  568. AuthenticationRepository = GetAuthenticationRepository();
  569. serviceCollection.AddSingleton(AuthenticationRepository);
  570. _userRepository = GetUserRepository();
  571. UserManager = new UserManager(
  572. LoggerFactory.CreateLogger<UserManager>(),
  573. _userRepository,
  574. XmlSerializer,
  575. NetworkManager,
  576. () => ImageProcessor,
  577. () => DtoService,
  578. this,
  579. JsonSerializer,
  580. FileSystemManager,
  581. cryptoProvider);
  582. serviceCollection.AddSingleton(UserManager);
  583. MediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  584. LoggerFactory.CreateLogger<MediaBrowser.MediaEncoding.Encoder.MediaEncoder>(),
  585. ServerConfigurationManager,
  586. FileSystemManager,
  587. LocalizationManager,
  588. () => SubtitleEncoder,
  589. startupConfig,
  590. StartupOptions.FFmpegPath);
  591. serviceCollection.AddSingleton(MediaEncoder);
  592. LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager, MediaEncoder);
  593. serviceCollection.AddSingleton(LibraryManager);
  594. var musicManager = new MusicManager(LibraryManager);
  595. serviceCollection.AddSingleton<IMusicManager>(musicManager);
  596. LibraryMonitor = new LibraryMonitor(LoggerFactory, LibraryManager, ServerConfigurationManager, FileSystemManager);
  597. serviceCollection.AddSingleton(LibraryMonitor);
  598. serviceCollection.AddSingleton<ISearchEngine>(new SearchEngine(LoggerFactory, LibraryManager, UserManager));
  599. CertificateInfo = GetCertificateInfo(true);
  600. Certificate = GetCertificate(CertificateInfo);
  601. serviceCollection.AddSingleton<ServiceController>();
  602. serviceCollection.AddSingleton<IHttpListener, WebSocketSharpListener>();
  603. serviceCollection.AddSingleton<IHttpServer, HttpListenerHost>();
  604. ImageProcessor = new ImageProcessor(LoggerFactory.CreateLogger<ImageProcessor>(), ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
  605. serviceCollection.AddSingleton(ImageProcessor);
  606. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  607. serviceCollection.AddSingleton(TVSeriesManager);
  608. DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager);
  609. serviceCollection.AddSingleton(DeviceManager);
  610. MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, () => MediaEncoder);
  611. serviceCollection.AddSingleton(MediaSourceManager);
  612. SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
  613. serviceCollection.AddSingleton(SubtitleManager);
  614. ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
  615. serviceCollection.AddSingleton(ProviderManager);
  616. DtoService = new DtoService(LoggerFactory, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ProviderManager, this, () => MediaSourceManager, () => LiveTvManager);
  617. serviceCollection.AddSingleton(DtoService);
  618. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, ProviderManager);
  619. serviceCollection.AddSingleton(ChannelManager);
  620. SessionManager = new SessionManager(
  621. LoggerFactory.CreateLogger<SessionManager>(),
  622. UserDataManager,
  623. LibraryManager,
  624. UserManager,
  625. musicManager,
  626. DtoService,
  627. ImageProcessor,
  628. this,
  629. AuthenticationRepository,
  630. DeviceManager,
  631. MediaSourceManager);
  632. serviceCollection.AddSingleton(SessionManager);
  633. serviceCollection.AddSingleton<IDlnaManager>(
  634. new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory, JsonSerializer, this));
  635. CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager);
  636. serviceCollection.AddSingleton(CollectionManager);
  637. serviceCollection.AddSingleton(typeof(IPlaylistManager), typeof(PlaylistManager));
  638. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, FileSystemManager, () => ChannelManager);
  639. serviceCollection.AddSingleton(LiveTvManager);
  640. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  641. serviceCollection.AddSingleton(UserViewManager);
  642. NotificationManager = new NotificationManager(
  643. LoggerFactory.CreateLogger<NotificationManager>(),
  644. UserManager,
  645. ServerConfigurationManager);
  646. serviceCollection.AddSingleton(NotificationManager);
  647. serviceCollection.AddSingleton<IDeviceDiscovery>(new DeviceDiscovery(ServerConfigurationManager));
  648. ChapterManager = new ChapterManager(ItemRepository);
  649. serviceCollection.AddSingleton(ChapterManager);
  650. EncodingManager = new MediaEncoder.EncodingManager(
  651. LoggerFactory.CreateLogger<MediaEncoder.EncodingManager>(),
  652. FileSystemManager,
  653. MediaEncoder,
  654. ChapterManager,
  655. LibraryManager);
  656. serviceCollection.AddSingleton(EncodingManager);
  657. var activityLogRepo = GetActivityLogRepository();
  658. serviceCollection.AddSingleton(activityLogRepo);
  659. serviceCollection.AddSingleton<IActivityManager>(new ActivityManager(LoggerFactory, activityLogRepo, UserManager));
  660. var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
  661. serviceCollection.AddSingleton<IAuthorizationContext>(authContext);
  662. serviceCollection.AddSingleton<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  663. AuthService = new AuthService(LoggerFactory.CreateLogger<AuthService>(), authContext, ServerConfigurationManager, SessionManager, NetworkManager);
  664. serviceCollection.AddSingleton(AuthService);
  665. SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(
  666. LibraryManager,
  667. LoggerFactory.CreateLogger<MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>(),
  668. ApplicationPaths,
  669. FileSystemManager,
  670. MediaEncoder,
  671. HttpClient,
  672. MediaSourceManager);
  673. serviceCollection.AddSingleton(SubtitleEncoder);
  674. serviceCollection.AddSingleton(typeof(IResourceFileManager), typeof(ResourceFileManager));
  675. serviceCollection.AddSingleton<EncodingHelper>();
  676. serviceCollection.AddSingleton(typeof(IAttachmentExtractor), typeof(MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor));
  677. _displayPreferencesRepository.Initialize();
  678. var userDataRepo = new SqliteUserDataRepository(LoggerFactory.CreateLogger<SqliteUserDataRepository>(), ApplicationPaths);
  679. SetStaticProperties();
  680. ((UserManager)UserManager).Initialize();
  681. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  682. ItemRepository.Initialize(userDataRepo, UserManager);
  683. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  684. }
  685. /// <summary>
  686. /// Create services registered with the service container that need to be initialized at application startup.
  687. /// </summary>
  688. public void InitializeServices()
  689. {
  690. HttpServer = Resolve<IHttpServer>();
  691. }
  692. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  693. {
  694. // Distinct these to prevent users from reporting problems that aren't actually problems
  695. var commandLineArgs = Environment
  696. .GetCommandLineArgs()
  697. .Distinct();
  698. // Get all 'JELLYFIN_' prefixed environment variables
  699. var allEnvVars = Environment.GetEnvironmentVariables();
  700. var jellyfinEnvVars = new Dictionary<object, object>();
  701. foreach (var key in allEnvVars.Keys)
  702. {
  703. if (key.ToString().StartsWith("JELLYFIN_", StringComparison.OrdinalIgnoreCase))
  704. {
  705. jellyfinEnvVars.Add(key, allEnvVars[key]);
  706. }
  707. }
  708. logger.LogInformation("Environment Variables: {EnvVars}", jellyfinEnvVars);
  709. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  710. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  711. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  712. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  713. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  714. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  715. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  716. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  717. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  718. }
  719. private X509Certificate2 GetCertificate(CertificateInfo info)
  720. {
  721. var certificateLocation = info?.Path;
  722. if (string.IsNullOrWhiteSpace(certificateLocation))
  723. {
  724. return null;
  725. }
  726. try
  727. {
  728. if (!File.Exists(certificateLocation))
  729. {
  730. return null;
  731. }
  732. // Don't use an empty string password
  733. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  734. var localCert = new X509Certificate2(certificateLocation, password);
  735. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  736. if (!localCert.HasPrivateKey)
  737. {
  738. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  739. return null;
  740. }
  741. return localCert;
  742. }
  743. catch (Exception ex)
  744. {
  745. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  746. return null;
  747. }
  748. }
  749. /// <summary>
  750. /// Gets the user repository.
  751. /// </summary>
  752. /// <returns><see cref="Task{SqliteUserRepository}" />.</returns>
  753. private SqliteUserRepository GetUserRepository()
  754. {
  755. var repo = new SqliteUserRepository(
  756. LoggerFactory.CreateLogger<SqliteUserRepository>(),
  757. ApplicationPaths);
  758. repo.Initialize();
  759. return repo;
  760. }
  761. private IAuthenticationRepository GetAuthenticationRepository()
  762. {
  763. var repo = new AuthenticationRepository(LoggerFactory, ServerConfigurationManager);
  764. repo.Initialize();
  765. return repo;
  766. }
  767. private IActivityRepository GetActivityLogRepository()
  768. {
  769. var repo = new ActivityRepository(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager);
  770. repo.Initialize();
  771. return repo;
  772. }
  773. /// <summary>
  774. /// Dirty hacks.
  775. /// </summary>
  776. private void SetStaticProperties()
  777. {
  778. ItemRepository.ImageProcessor = ImageProcessor;
  779. // For now there's no real way to inject these properly
  780. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  781. BaseItem.ConfigurationManager = ServerConfigurationManager;
  782. BaseItem.LibraryManager = LibraryManager;
  783. BaseItem.ProviderManager = ProviderManager;
  784. BaseItem.LocalizationManager = LocalizationManager;
  785. BaseItem.ItemRepository = ItemRepository;
  786. User.UserManager = UserManager;
  787. BaseItem.FileSystem = FileSystemManager;
  788. BaseItem.UserDataManager = UserDataManager;
  789. BaseItem.ChannelManager = ChannelManager;
  790. Video.LiveTvManager = LiveTvManager;
  791. Folder.UserViewManager = UserViewManager;
  792. UserView.TVSeriesManager = TVSeriesManager;
  793. UserView.CollectionManager = CollectionManager;
  794. BaseItem.MediaSourceManager = MediaSourceManager;
  795. CollectionFolder.XmlSerializer = XmlSerializer;
  796. CollectionFolder.JsonSerializer = JsonSerializer;
  797. CollectionFolder.ApplicationHost = this;
  798. AuthenticatedAttribute.AuthService = AuthService;
  799. }
  800. private async void PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> args)
  801. {
  802. string dir = Path.Combine(ApplicationPaths.PluginsPath, args.Argument.name);
  803. var types = Directory.EnumerateFiles(dir, "*.dll", SearchOption.AllDirectories)
  804. .Select(Assembly.LoadFrom)
  805. .SelectMany(x => x.ExportedTypes)
  806. .Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface && !x.IsGenericType)
  807. .ToArray();
  808. int oldLen = _allConcreteTypes.Length;
  809. Array.Resize(ref _allConcreteTypes, oldLen + types.Length);
  810. types.CopyTo(_allConcreteTypes, oldLen);
  811. var plugins = types.Where(x => x.IsAssignableFrom(typeof(IPlugin)))
  812. .Select(CreateInstanceSafe)
  813. .Where(x => x != null)
  814. .Cast<IPlugin>()
  815. .Select(LoadPlugin)
  816. .Where(x => x != null)
  817. .ToArray();
  818. oldLen = _plugins.Length;
  819. Array.Resize(ref _plugins, oldLen + plugins.Length);
  820. plugins.CopyTo(_plugins, oldLen);
  821. var entries = types.Where(x => x.IsAssignableFrom(typeof(IServerEntryPoint)))
  822. .Select(CreateInstanceSafe)
  823. .Where(x => x != null)
  824. .Cast<IServerEntryPoint>()
  825. .ToList();
  826. await Task.WhenAll(StartEntryPoints(entries, true)).ConfigureAwait(false);
  827. await Task.WhenAll(StartEntryPoints(entries, false)).ConfigureAwait(false);
  828. }
  829. /// <summary>
  830. /// Finds the parts.
  831. /// </summary>
  832. public void FindParts()
  833. {
  834. InstallationManager = ServiceProvider.GetService<IInstallationManager>();
  835. InstallationManager.PluginInstalled += PluginInstalled;
  836. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  837. {
  838. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  839. ConfigurationManager.SaveConfiguration();
  840. }
  841. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  842. _plugins = GetExports<IPlugin>()
  843. .Select(LoadPlugin)
  844. .Where(i => i != null)
  845. .ToArray();
  846. HttpServer.Init(GetExportTypes<IService>(), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  847. LibraryManager.AddParts(
  848. GetExports<IResolverIgnoreRule>(),
  849. GetExports<IItemResolver>(),
  850. GetExports<IIntroProvider>(),
  851. GetExports<IBaseItemComparer>(),
  852. GetExports<ILibraryPostScanTask>());
  853. ProviderManager.AddParts(
  854. GetExports<IImageProvider>(),
  855. GetExports<IMetadataService>(),
  856. GetExports<IMetadataProvider>(),
  857. GetExports<IMetadataSaver>(),
  858. GetExports<IExternalId>());
  859. LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  860. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  861. ChannelManager.AddParts(GetExports<IChannel>());
  862. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  863. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  864. UserManager.AddParts(GetExports<IAuthenticationProvider>(), GetExports<IPasswordResetProvider>());
  865. IsoManager.AddParts(GetExports<IIsoMounter>());
  866. }
  867. private IPlugin LoadPlugin(IPlugin plugin)
  868. {
  869. try
  870. {
  871. if (plugin is IPluginAssembly assemblyPlugin)
  872. {
  873. var assembly = plugin.GetType().Assembly;
  874. var assemblyName = assembly.GetName();
  875. var assemblyFilePath = assembly.Location;
  876. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  877. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  878. try
  879. {
  880. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  881. if (idAttributes.Length > 0)
  882. {
  883. var attribute = (GuidAttribute)idAttributes[0];
  884. var assemblyId = new Guid(attribute.Value);
  885. assemblyPlugin.SetId(assemblyId);
  886. }
  887. }
  888. catch (Exception ex)
  889. {
  890. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  891. }
  892. }
  893. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  894. {
  895. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  896. }
  897. }
  898. catch (Exception ex)
  899. {
  900. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  901. return null;
  902. }
  903. return plugin;
  904. }
  905. /// <summary>
  906. /// Discovers the types.
  907. /// </summary>
  908. protected void DiscoverTypes()
  909. {
  910. Logger.LogInformation("Loading assemblies");
  911. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  912. }
  913. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  914. {
  915. foreach (var ass in assemblies)
  916. {
  917. Type[] exportedTypes;
  918. try
  919. {
  920. exportedTypes = ass.GetExportedTypes();
  921. }
  922. catch (FileNotFoundException ex)
  923. {
  924. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  925. continue;
  926. }
  927. foreach (Type type in exportedTypes)
  928. {
  929. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  930. {
  931. yield return type;
  932. }
  933. }
  934. }
  935. }
  936. private CertificateInfo CertificateInfo { get; set; }
  937. public X509Certificate2 Certificate { get; private set; }
  938. private IEnumerable<string> GetUrlPrefixes()
  939. {
  940. var hosts = new[] { "+" };
  941. return hosts.SelectMany(i =>
  942. {
  943. var prefixes = new List<string>
  944. {
  945. "http://" + i + ":" + HttpPort + "/"
  946. };
  947. if (CertificateInfo != null)
  948. {
  949. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  950. }
  951. return prefixes;
  952. });
  953. }
  954. private CertificateInfo GetCertificateInfo(bool generateCertificate)
  955. {
  956. // Custom cert
  957. return new CertificateInfo
  958. {
  959. Path = ServerConfigurationManager.Configuration.CertificatePath,
  960. Password = ServerConfigurationManager.Configuration.CertificatePassword
  961. };
  962. }
  963. /// <summary>
  964. /// Called when [configuration updated].
  965. /// </summary>
  966. /// <param name="sender">The sender.</param>
  967. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  968. protected void OnConfigurationUpdated(object sender, EventArgs e)
  969. {
  970. var requiresRestart = false;
  971. // Don't do anything if these haven't been set yet
  972. if (HttpPort != 0 && HttpsPort != 0)
  973. {
  974. // Need to restart if ports have changed
  975. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  976. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  977. {
  978. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  979. {
  980. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  981. ServerConfigurationManager.SaveConfiguration();
  982. requiresRestart = true;
  983. }
  984. }
  985. }
  986. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  987. {
  988. requiresRestart = true;
  989. }
  990. var currentCertPath = CertificateInfo?.Path;
  991. var newCertInfo = GetCertificateInfo(false);
  992. var newCertPath = newCertInfo?.Path;
  993. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  994. {
  995. requiresRestart = true;
  996. }
  997. if (requiresRestart)
  998. {
  999. Logger.LogInformation("App needs to be restarted due to configuration change.");
  1000. NotifyPendingRestart();
  1001. }
  1002. }
  1003. /// <summary>
  1004. /// Notifies that the kernel that a change has been made that requires a restart
  1005. /// </summary>
  1006. public void NotifyPendingRestart()
  1007. {
  1008. Logger.LogInformation("App needs to be restarted.");
  1009. var changed = !HasPendingRestart;
  1010. HasPendingRestart = true;
  1011. if (changed)
  1012. {
  1013. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  1014. }
  1015. }
  1016. /// <summary>
  1017. /// Restarts this instance.
  1018. /// </summary>
  1019. public void Restart()
  1020. {
  1021. if (!CanSelfRestart)
  1022. {
  1023. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  1024. }
  1025. if (IsShuttingDown)
  1026. {
  1027. return;
  1028. }
  1029. IsShuttingDown = true;
  1030. Task.Run(async () =>
  1031. {
  1032. try
  1033. {
  1034. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  1035. }
  1036. catch (Exception ex)
  1037. {
  1038. Logger.LogError(ex, "Error sending server restart notification");
  1039. }
  1040. Logger.LogInformation("Calling RestartInternal");
  1041. RestartInternal();
  1042. });
  1043. }
  1044. protected abstract void RestartInternal();
  1045. /// <summary>
  1046. /// Gets the composable part assemblies.
  1047. /// </summary>
  1048. /// <returns>IEnumerable{Assembly}.</returns>
  1049. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  1050. {
  1051. if (Directory.Exists(ApplicationPaths.PluginsPath))
  1052. {
  1053. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  1054. {
  1055. Assembly plugAss;
  1056. try
  1057. {
  1058. plugAss = Assembly.LoadFrom(file);
  1059. }
  1060. catch (FileLoadException ex)
  1061. {
  1062. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  1063. continue;
  1064. }
  1065. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  1066. yield return plugAss;
  1067. }
  1068. }
  1069. // Include composable parts in the Api assembly
  1070. yield return typeof(ApiEntryPoint).Assembly;
  1071. // Include composable parts in the Dashboard assembly
  1072. yield return typeof(DashboardService).Assembly;
  1073. // Include composable parts in the Model assembly
  1074. yield return typeof(SystemInfo).Assembly;
  1075. // Include composable parts in the Common assembly
  1076. yield return typeof(IApplicationHost).Assembly;
  1077. // Include composable parts in the Controller assembly
  1078. yield return typeof(IServerApplicationHost).Assembly;
  1079. // Include composable parts in the Providers assembly
  1080. yield return typeof(ProviderUtils).Assembly;
  1081. // Include composable parts in the Photos assembly
  1082. yield return typeof(PhotoProvider).Assembly;
  1083. // Emby.Server implementations
  1084. yield return typeof(InstallationManager).Assembly;
  1085. // MediaEncoding
  1086. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  1087. // Dlna
  1088. yield return typeof(DlnaEntryPoint).Assembly;
  1089. // Local metadata
  1090. yield return typeof(BoxSetXmlSaver).Assembly;
  1091. // Notifications
  1092. yield return typeof(NotificationManager).Assembly;
  1093. // Xbmc
  1094. yield return typeof(ArtistNfoProvider).Assembly;
  1095. foreach (var i in GetAssembliesWithPartsInternal())
  1096. {
  1097. yield return i;
  1098. }
  1099. }
  1100. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  1101. /// <summary>
  1102. /// Gets the system status.
  1103. /// </summary>
  1104. /// <param name="cancellationToken">The cancellation token.</param>
  1105. /// <returns>SystemInfo.</returns>
  1106. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  1107. {
  1108. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1109. var transcodingTempPath = ConfigurationManager.GetTranscodePath();
  1110. return new SystemInfo
  1111. {
  1112. HasPendingRestart = HasPendingRestart,
  1113. IsShuttingDown = IsShuttingDown,
  1114. Version = ApplicationVersionString,
  1115. WebSocketPortNumber = HttpPort,
  1116. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  1117. Id = SystemId,
  1118. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1119. WebPath = ApplicationPaths.WebPath,
  1120. LogPath = ApplicationPaths.LogDirectoryPath,
  1121. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  1122. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1123. CachePath = ApplicationPaths.CachePath,
  1124. HttpServerPortNumber = HttpPort,
  1125. SupportsHttps = SupportsHttps,
  1126. HttpsPortNumber = HttpsPort,
  1127. OperatingSystem = OperatingSystem.Id.ToString(),
  1128. OperatingSystemDisplayName = OperatingSystem.Name,
  1129. CanSelfRestart = CanSelfRestart,
  1130. CanLaunchWebBrowser = CanLaunchWebBrowser,
  1131. HasUpdateAvailable = HasUpdateAvailable,
  1132. TranscodingTempPath = transcodingTempPath,
  1133. ServerName = FriendlyName,
  1134. LocalAddress = localAddress,
  1135. SupportsLibraryMonitor = true,
  1136. EncoderLocation = MediaEncoder.EncoderLocation,
  1137. SystemArchitecture = RuntimeInformation.OSArchitecture,
  1138. SystemUpdateLevel = SystemUpdateLevel,
  1139. PackageName = StartupOptions.PackageName
  1140. };
  1141. }
  1142. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  1143. => NetworkManager.GetMacAddresses()
  1144. .Select(i => new WakeOnLanInfo(i))
  1145. .ToList();
  1146. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1147. {
  1148. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1149. return new PublicSystemInfo
  1150. {
  1151. Version = ApplicationVersionString,
  1152. ProductName = ApplicationProductName,
  1153. Id = SystemId,
  1154. OperatingSystem = OperatingSystem.Id.ToString(),
  1155. ServerName = FriendlyName,
  1156. LocalAddress = localAddress
  1157. };
  1158. }
  1159. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1160. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1161. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1162. {
  1163. try
  1164. {
  1165. // Return the first matched address, if found, or the first known local address
  1166. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1167. foreach (var address in addresses)
  1168. {
  1169. return GetLocalApiUrl(address);
  1170. }
  1171. return null;
  1172. }
  1173. catch (Exception ex)
  1174. {
  1175. Logger.LogError(ex, "Error getting local Ip address information");
  1176. }
  1177. return null;
  1178. }
  1179. /// <summary>
  1180. /// Removes the scope id from IPv6 addresses.
  1181. /// </summary>
  1182. /// <param name="address">The IPv6 address.</param>
  1183. /// <returns>The IPv6 address without the scope id.</returns>
  1184. private ReadOnlySpan<char> RemoveScopeId(ReadOnlySpan<char> address)
  1185. {
  1186. var index = address.IndexOf('%');
  1187. if (index == -1)
  1188. {
  1189. return address;
  1190. }
  1191. return address.Slice(0, index);
  1192. }
  1193. /// <inheritdoc />
  1194. public string GetLocalApiUrl(IPAddress ipAddress)
  1195. {
  1196. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1197. {
  1198. var str = RemoveScopeId(ipAddress.ToString());
  1199. Span<char> span = new char[str.Length + 2];
  1200. span[0] = '[';
  1201. str.CopyTo(span.Slice(1));
  1202. span[^1] = ']';
  1203. return GetLocalApiUrl(span);
  1204. }
  1205. return GetLocalApiUrl(ipAddress.ToString());
  1206. }
  1207. /// <inheritdoc />
  1208. public string GetLocalApiUrl(ReadOnlySpan<char> host)
  1209. {
  1210. var url = new StringBuilder(64);
  1211. url.Append(EnableHttps ? "https://" : "http://")
  1212. .Append(host)
  1213. .Append(':')
  1214. .Append(EnableHttps ? HttpsPort : HttpPort);
  1215. string baseUrl = ServerConfigurationManager.Configuration.BaseUrl;
  1216. if (baseUrl.Length != 0)
  1217. {
  1218. url.Append(baseUrl);
  1219. }
  1220. return url.ToString();
  1221. }
  1222. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1223. {
  1224. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1225. }
  1226. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1227. {
  1228. var addresses = ServerConfigurationManager
  1229. .Configuration
  1230. .LocalNetworkAddresses
  1231. .Select(NormalizeConfiguredLocalAddress)
  1232. .Where(i => i != null)
  1233. .ToList();
  1234. if (addresses.Count == 0)
  1235. {
  1236. addresses.AddRange(NetworkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1237. }
  1238. var resultList = new List<IPAddress>();
  1239. foreach (var address in addresses)
  1240. {
  1241. if (!allowLoopback)
  1242. {
  1243. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1244. {
  1245. continue;
  1246. }
  1247. }
  1248. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1249. if (valid)
  1250. {
  1251. resultList.Add(address);
  1252. if (limit > 0 && resultList.Count >= limit)
  1253. {
  1254. return resultList;
  1255. }
  1256. }
  1257. }
  1258. return resultList;
  1259. }
  1260. public IPAddress NormalizeConfiguredLocalAddress(string address)
  1261. {
  1262. var index = address.Trim('/').IndexOf('/');
  1263. if (index != -1)
  1264. {
  1265. address = address.Substring(index + 1);
  1266. }
  1267. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1268. {
  1269. return result;
  1270. }
  1271. return null;
  1272. }
  1273. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1274. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1275. {
  1276. if (address.Equals(IPAddress.Loopback)
  1277. || address.Equals(IPAddress.IPv6Loopback))
  1278. {
  1279. return true;
  1280. }
  1281. var apiUrl = GetLocalApiUrl(address);
  1282. apiUrl += "/system/ping";
  1283. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1284. {
  1285. return cachedResult;
  1286. }
  1287. try
  1288. {
  1289. using (var response = await HttpClient.SendAsync(
  1290. new HttpRequestOptions
  1291. {
  1292. Url = apiUrl,
  1293. LogErrorResponseBody = false,
  1294. BufferContent = false,
  1295. CancellationToken = cancellationToken
  1296. }, HttpMethod.Post).ConfigureAwait(false))
  1297. {
  1298. using (var reader = new StreamReader(response.Content))
  1299. {
  1300. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1301. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1302. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1303. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1304. return valid;
  1305. }
  1306. }
  1307. }
  1308. catch (OperationCanceledException)
  1309. {
  1310. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1311. throw;
  1312. }
  1313. catch (Exception ex)
  1314. {
  1315. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1316. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1317. return false;
  1318. }
  1319. }
  1320. public string FriendlyName =>
  1321. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1322. ? Environment.MachineName
  1323. : ServerConfigurationManager.Configuration.ServerName;
  1324. /// <summary>
  1325. /// Shuts down.
  1326. /// </summary>
  1327. public async Task Shutdown()
  1328. {
  1329. if (IsShuttingDown)
  1330. {
  1331. return;
  1332. }
  1333. IsShuttingDown = true;
  1334. try
  1335. {
  1336. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1337. }
  1338. catch (Exception ex)
  1339. {
  1340. Logger.LogError(ex, "Error sending server shutdown notification");
  1341. }
  1342. ShutdownInternal();
  1343. }
  1344. protected abstract void ShutdownInternal();
  1345. public event EventHandler HasUpdateAvailableChanged;
  1346. private bool _hasUpdateAvailable;
  1347. public bool HasUpdateAvailable
  1348. {
  1349. get => _hasUpdateAvailable;
  1350. set
  1351. {
  1352. var fireEvent = value && !_hasUpdateAvailable;
  1353. _hasUpdateAvailable = value;
  1354. if (fireEvent)
  1355. {
  1356. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1357. }
  1358. }
  1359. }
  1360. /// <summary>
  1361. /// Removes the plugin.
  1362. /// </summary>
  1363. /// <param name="plugin">The plugin.</param>
  1364. public void RemovePlugin(IPlugin plugin)
  1365. {
  1366. var list = _plugins.ToList();
  1367. list.Remove(plugin);
  1368. _plugins = list.ToArray();
  1369. }
  1370. public virtual void LaunchUrl(string url)
  1371. {
  1372. if (!CanLaunchWebBrowser)
  1373. {
  1374. throw new NotSupportedException();
  1375. }
  1376. var processStartInfo = new ProcessStartInfo
  1377. {
  1378. FileName = url,
  1379. UseShellExecute = true,
  1380. ErrorDialog = false
  1381. };
  1382. var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true };
  1383. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1384. try
  1385. {
  1386. process.Start();
  1387. }
  1388. catch (Exception ex)
  1389. {
  1390. Logger.LogError(ex, "Error launching url: {url}", url);
  1391. throw;
  1392. }
  1393. }
  1394. public virtual void EnableLoopback(string appName)
  1395. {
  1396. }
  1397. private bool _disposed = false;
  1398. /// <summary>
  1399. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1400. /// </summary>
  1401. public void Dispose()
  1402. {
  1403. Dispose(true);
  1404. GC.SuppressFinalize(this);
  1405. }
  1406. /// <summary>
  1407. /// Releases unmanaged and - optionally - managed resources.
  1408. /// </summary>
  1409. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1410. protected virtual void Dispose(bool dispose)
  1411. {
  1412. if (_disposed)
  1413. {
  1414. return;
  1415. }
  1416. if (dispose)
  1417. {
  1418. var type = GetType();
  1419. Logger.LogInformation("Disposing {Type}", type.Name);
  1420. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1421. _disposableParts.Clear();
  1422. foreach (var part in parts)
  1423. {
  1424. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1425. try
  1426. {
  1427. part.Dispose();
  1428. }
  1429. catch (Exception ex)
  1430. {
  1431. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1432. }
  1433. }
  1434. _userRepository?.Dispose();
  1435. _displayPreferencesRepository?.Dispose();
  1436. }
  1437. _userRepository = null;
  1438. _displayPreferencesRepository = null;
  1439. _disposed = true;
  1440. }
  1441. }
  1442. internal class CertificateInfo
  1443. {
  1444. public string Path { get; set; }
  1445. public string Password { get; set; }
  1446. }
  1447. }