ApplicationHost.cs 66 KB

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