ApplicationHost.cs 66 KB

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