ApplicationHost.cs 66 KB

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