ApplicationHost.cs 66 KB

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