ApplicationHost.cs 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813
  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. // TODO wtaylor: investigate use of second music manager
  612. var musicManager = new MusicManager(LibraryManager);
  613. serviceCollection.AddSingleton<IMusicManager>(new MusicManager(LibraryManager));
  614. LibraryMonitor = new LibraryMonitor(LoggerFactory, LibraryManager, ServerConfigurationManager, FileSystemManager);
  615. serviceCollection.AddSingleton(LibraryMonitor);
  616. serviceCollection.AddSingleton<ISearchEngine>(new SearchEngine(LoggerFactory, LibraryManager, UserManager));
  617. CertificateInfo = GetCertificateInfo(true);
  618. Certificate = GetCertificate(CertificateInfo);
  619. HttpServer = new HttpListenerHost(
  620. this,
  621. LoggerFactory.CreateLogger<HttpListenerHost>(),
  622. ServerConfigurationManager,
  623. _configuration,
  624. NetworkManager,
  625. JsonSerializer,
  626. XmlSerializer,
  627. CreateHttpListener())
  628. {
  629. GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading")
  630. };
  631. serviceCollection.AddSingleton(HttpServer);
  632. ImageProcessor = new ImageProcessor(LoggerFactory.CreateLogger<ImageProcessor>(), ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
  633. serviceCollection.AddSingleton(ImageProcessor);
  634. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  635. serviceCollection.AddSingleton(TVSeriesManager);
  636. DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager);
  637. serviceCollection.AddSingleton(DeviceManager);
  638. MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, () => MediaEncoder);
  639. serviceCollection.AddSingleton(MediaSourceManager);
  640. SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
  641. serviceCollection.AddSingleton(SubtitleManager);
  642. ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
  643. serviceCollection.AddSingleton(ProviderManager);
  644. DtoService = new DtoService(LoggerFactory, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ProviderManager, this, () => MediaSourceManager, () => LiveTvManager);
  645. serviceCollection.AddSingleton(DtoService);
  646. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, ProviderManager);
  647. serviceCollection.AddSingleton(ChannelManager);
  648. SessionManager = new SessionManager(UserDataManager, LoggerFactory, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, this, AuthenticationRepository, DeviceManager, MediaSourceManager);
  649. serviceCollection.AddSingleton(SessionManager);
  650. serviceCollection.AddSingleton<IDlnaManager>(
  651. new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory, JsonSerializer, this));
  652. CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager);
  653. serviceCollection.AddSingleton(CollectionManager);
  654. serviceCollection.AddSingleton(typeof(IPlaylistManager), typeof(PlaylistManager));
  655. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, FileSystemManager, () => ChannelManager);
  656. serviceCollection.AddSingleton(LiveTvManager);
  657. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  658. serviceCollection.AddSingleton(UserViewManager);
  659. NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager);
  660. serviceCollection.AddSingleton(NotificationManager);
  661. serviceCollection.AddSingleton<IDeviceDiscovery>(new DeviceDiscovery(ServerConfigurationManager));
  662. ChapterManager = new ChapterManager(LibraryManager, LoggerFactory, ServerConfigurationManager, ItemRepository);
  663. serviceCollection.AddSingleton(ChapterManager);
  664. MediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  665. LoggerFactory,
  666. JsonSerializer,
  667. StartupOptions.FFmpegPath,
  668. ServerConfigurationManager,
  669. FileSystemManager,
  670. () => SubtitleEncoder,
  671. () => MediaSourceManager,
  672. ProcessFactory,
  673. 5000,
  674. LocalizationManager);
  675. serviceCollection.AddSingleton(MediaEncoder);
  676. EncodingManager = new MediaEncoder.EncodingManager(FileSystemManager, LoggerFactory, MediaEncoder, ChapterManager, LibraryManager);
  677. serviceCollection.AddSingleton(EncodingManager);
  678. var activityLogRepo = GetActivityLogRepository();
  679. serviceCollection.AddSingleton(activityLogRepo);
  680. serviceCollection.AddSingleton<IActivityManager>(new ActivityManager(LoggerFactory, activityLogRepo, UserManager));
  681. var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
  682. serviceCollection.AddSingleton<IAuthorizationContext>(authContext);
  683. serviceCollection.AddSingleton<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  684. AuthService = new AuthService(LoggerFactory.CreateLogger<AuthService>(), authContext, ServerConfigurationManager, SessionManager, NetworkManager);
  685. serviceCollection.AddSingleton(AuthService);
  686. SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory, ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory);
  687. serviceCollection.AddSingleton(SubtitleEncoder);
  688. serviceCollection.AddSingleton(typeof(IResourceFileManager), typeof(ResourceFileManager));
  689. _displayPreferencesRepository.Initialize();
  690. var userDataRepo = new SqliteUserDataRepository(LoggerFactory.CreateLogger<SqliteUserDataRepository>(), ApplicationPaths);
  691. SetStaticProperties();
  692. ((UserManager)UserManager).Initialize();
  693. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  694. ItemRepository.Initialize(userDataRepo, UserManager);
  695. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  696. }
  697. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  698. {
  699. // Distinct these to prevent users from reporting problems that aren't actually problems
  700. var commandLineArgs = Environment
  701. .GetCommandLineArgs()
  702. .Distinct();
  703. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  704. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  705. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  706. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  707. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  708. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  709. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  710. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  711. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  712. }
  713. private X509Certificate2 GetCertificate(CertificateInfo info)
  714. {
  715. var certificateLocation = info?.Path;
  716. if (string.IsNullOrWhiteSpace(certificateLocation))
  717. {
  718. return null;
  719. }
  720. try
  721. {
  722. if (!File.Exists(certificateLocation))
  723. {
  724. return null;
  725. }
  726. // Don't use an empty string password
  727. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  728. var localCert = new X509Certificate2(certificateLocation, password);
  729. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  730. if (!localCert.HasPrivateKey)
  731. {
  732. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  733. return null;
  734. }
  735. return localCert;
  736. }
  737. catch (Exception ex)
  738. {
  739. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  740. return null;
  741. }
  742. }
  743. /// <summary>
  744. /// Gets the user repository.
  745. /// </summary>
  746. /// <returns><see cref="Task{SqliteUserRepository}" />.</returns>
  747. private SqliteUserRepository GetUserRepository()
  748. {
  749. var repo = new SqliteUserRepository(
  750. LoggerFactory.CreateLogger<SqliteUserRepository>(),
  751. ApplicationPaths);
  752. repo.Initialize();
  753. return repo;
  754. }
  755. private IAuthenticationRepository GetAuthenticationRepository()
  756. {
  757. var repo = new AuthenticationRepository(LoggerFactory, ServerConfigurationManager);
  758. repo.Initialize();
  759. return repo;
  760. }
  761. private IActivityRepository GetActivityLogRepository()
  762. {
  763. var repo = new ActivityRepository(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager);
  764. repo.Initialize();
  765. return repo;
  766. }
  767. /// <summary>
  768. /// Dirty hacks.
  769. /// </summary>
  770. private void SetStaticProperties()
  771. {
  772. ItemRepository.ImageProcessor = ImageProcessor;
  773. // For now there's no real way to inject these properly
  774. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  775. BaseItem.ConfigurationManager = ServerConfigurationManager;
  776. BaseItem.LibraryManager = LibraryManager;
  777. BaseItem.ProviderManager = ProviderManager;
  778. BaseItem.LocalizationManager = LocalizationManager;
  779. BaseItem.ItemRepository = ItemRepository;
  780. User.UserManager = UserManager;
  781. BaseItem.FileSystem = FileSystemManager;
  782. BaseItem.UserDataManager = UserDataManager;
  783. BaseItem.ChannelManager = ChannelManager;
  784. Video.LiveTvManager = LiveTvManager;
  785. Folder.UserViewManager = UserViewManager;
  786. UserView.TVSeriesManager = TVSeriesManager;
  787. UserView.CollectionManager = CollectionManager;
  788. BaseItem.MediaSourceManager = MediaSourceManager;
  789. CollectionFolder.XmlSerializer = XmlSerializer;
  790. CollectionFolder.JsonSerializer = JsonSerializer;
  791. CollectionFolder.ApplicationHost = this;
  792. AuthenticatedAttribute.AuthService = AuthService;
  793. }
  794. private async void PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> args)
  795. {
  796. string dir = Path.Combine(ApplicationPaths.PluginsPath, args.Argument.name);
  797. var types = Directory.EnumerateFiles(dir, "*.dll", SearchOption.AllDirectories)
  798. .Select(x => Assembly.LoadFrom(x))
  799. .SelectMany(x => x.ExportedTypes)
  800. .Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface && !x.IsGenericType)
  801. .ToArray();
  802. int oldLen = _allConcreteTypes.Length;
  803. Array.Resize(ref _allConcreteTypes, oldLen + types.Length);
  804. types.CopyTo(_allConcreteTypes, oldLen);
  805. var plugins = types.Where(x => x.IsAssignableFrom(typeof(IPlugin)))
  806. .Select(CreateInstanceSafe)
  807. .Where(x => x != null)
  808. .Cast<IPlugin>()
  809. .Select(LoadPlugin)
  810. .Where(x => x != null)
  811. .ToArray();
  812. oldLen = _plugins.Length;
  813. Array.Resize(ref _plugins, oldLen + plugins.Length);
  814. plugins.CopyTo(_plugins, oldLen);
  815. var entries = types.Where(x => x.IsAssignableFrom(typeof(IServerEntryPoint)))
  816. .Select(CreateInstanceSafe)
  817. .Where(x => x != null)
  818. .Cast<IServerEntryPoint>()
  819. .ToList();
  820. await Task.WhenAll(StartEntryPoints(entries, true)).ConfigureAwait(false);
  821. await Task.WhenAll(StartEntryPoints(entries, false)).ConfigureAwait(false);
  822. }
  823. /// <summary>
  824. /// Finds the parts.
  825. /// </summary>
  826. public void FindParts()
  827. {
  828. InstallationManager = ServiceProvider.GetService<IInstallationManager>();
  829. InstallationManager.PluginInstalled += PluginInstalled;
  830. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  831. {
  832. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  833. ConfigurationManager.SaveConfiguration();
  834. }
  835. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  836. Plugins = GetExports<IPlugin>()
  837. .Select(LoadPlugin)
  838. .Where(i => i != null)
  839. .ToArray();
  840. HttpServer.Init(GetExports<IService>(false), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  841. LibraryManager.AddParts(
  842. GetExports<IResolverIgnoreRule>(),
  843. GetExports<IItemResolver>(),
  844. GetExports<IIntroProvider>(),
  845. GetExports<IBaseItemComparer>(),
  846. GetExports<ILibraryPostScanTask>());
  847. ProviderManager.AddParts(
  848. GetExports<IImageProvider>(),
  849. GetExports<IMetadataService>(),
  850. GetExports<IMetadataProvider>(),
  851. GetExports<IMetadataSaver>(),
  852. GetExports<IExternalId>());
  853. ImageProcessor.ImageEnhancers = GetExports<IImageEnhancer>();
  854. LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  855. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  856. ChannelManager.AddParts(GetExports<IChannel>());
  857. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  858. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  859. UserManager.AddParts(GetExports<IAuthenticationProvider>(), GetExports<IPasswordResetProvider>());
  860. IsoManager.AddParts(GetExports<IIsoMounter>());
  861. }
  862. private IPlugin LoadPlugin(IPlugin plugin)
  863. {
  864. try
  865. {
  866. if (plugin is IPluginAssembly assemblyPlugin)
  867. {
  868. var assembly = plugin.GetType().Assembly;
  869. var assemblyName = assembly.GetName();
  870. var assemblyFilePath = assembly.Location;
  871. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  872. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  873. try
  874. {
  875. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  876. if (idAttributes.Length > 0)
  877. {
  878. var attribute = (GuidAttribute)idAttributes[0];
  879. var assemblyId = new Guid(attribute.Value);
  880. assemblyPlugin.SetId(assemblyId);
  881. }
  882. }
  883. catch (Exception ex)
  884. {
  885. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  886. }
  887. }
  888. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  889. {
  890. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  891. }
  892. }
  893. catch (Exception ex)
  894. {
  895. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  896. return null;
  897. }
  898. return plugin;
  899. }
  900. /// <summary>
  901. /// Discovers the types.
  902. /// </summary>
  903. protected void DiscoverTypes()
  904. {
  905. Logger.LogInformation("Loading assemblies");
  906. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  907. }
  908. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  909. {
  910. foreach (var ass in assemblies)
  911. {
  912. Type[] exportedTypes;
  913. try
  914. {
  915. exportedTypes = ass.GetExportedTypes();
  916. }
  917. catch (TypeLoadException ex)
  918. {
  919. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  920. continue;
  921. }
  922. foreach (Type type in exportedTypes)
  923. {
  924. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  925. {
  926. yield return type;
  927. }
  928. }
  929. }
  930. }
  931. private CertificateInfo CertificateInfo { get; set; }
  932. public X509Certificate2 Certificate { get; private set; }
  933. private IEnumerable<string> GetUrlPrefixes()
  934. {
  935. var hosts = new[] { "+" };
  936. return hosts.SelectMany(i =>
  937. {
  938. var prefixes = new List<string>
  939. {
  940. "http://" + i + ":" + HttpPort + "/"
  941. };
  942. if (CertificateInfo != null)
  943. {
  944. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  945. }
  946. return prefixes;
  947. });
  948. }
  949. protected IHttpListener CreateHttpListener() => new WebSocketSharpListener(Logger);
  950. private CertificateInfo GetCertificateInfo(bool generateCertificate)
  951. {
  952. // Custom cert
  953. return new CertificateInfo
  954. {
  955. Path = ServerConfigurationManager.Configuration.CertificatePath,
  956. Password = ServerConfigurationManager.Configuration.CertificatePassword
  957. };
  958. }
  959. /// <summary>
  960. /// Called when [configuration updated].
  961. /// </summary>
  962. /// <param name="sender">The sender.</param>
  963. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  964. protected void OnConfigurationUpdated(object sender, EventArgs e)
  965. {
  966. var requiresRestart = false;
  967. // Don't do anything if these haven't been set yet
  968. if (HttpPort != 0 && HttpsPort != 0)
  969. {
  970. // Need to restart if ports have changed
  971. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  972. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  973. {
  974. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  975. {
  976. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  977. ServerConfigurationManager.SaveConfiguration();
  978. requiresRestart = true;
  979. }
  980. }
  981. }
  982. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  983. {
  984. requiresRestart = true;
  985. }
  986. var currentCertPath = CertificateInfo?.Path;
  987. var newCertInfo = GetCertificateInfo(false);
  988. var newCertPath = newCertInfo?.Path;
  989. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  990. {
  991. requiresRestart = true;
  992. }
  993. if (requiresRestart)
  994. {
  995. Logger.LogInformation("App needs to be restarted due to configuration change.");
  996. NotifyPendingRestart();
  997. }
  998. }
  999. /// <summary>
  1000. /// Notifies that the kernel that a change has been made that requires a restart
  1001. /// </summary>
  1002. public void NotifyPendingRestart()
  1003. {
  1004. Logger.LogInformation("App needs to be restarted.");
  1005. var changed = !HasPendingRestart;
  1006. HasPendingRestart = true;
  1007. if (changed)
  1008. {
  1009. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  1010. }
  1011. }
  1012. /// <summary>
  1013. /// Restarts this instance.
  1014. /// </summary>
  1015. public void Restart()
  1016. {
  1017. if (!CanSelfRestart)
  1018. {
  1019. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  1020. }
  1021. if (IsShuttingDown)
  1022. {
  1023. return;
  1024. }
  1025. IsShuttingDown = true;
  1026. Task.Run(async () =>
  1027. {
  1028. try
  1029. {
  1030. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  1031. }
  1032. catch (Exception ex)
  1033. {
  1034. Logger.LogError(ex, "Error sending server restart notification");
  1035. }
  1036. Logger.LogInformation("Calling RestartInternal");
  1037. RestartInternal();
  1038. });
  1039. }
  1040. protected abstract void RestartInternal();
  1041. /// <summary>
  1042. /// Gets the composable part assemblies.
  1043. /// </summary>
  1044. /// <returns>IEnumerable{Assembly}.</returns>
  1045. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  1046. {
  1047. if (Directory.Exists(ApplicationPaths.PluginsPath))
  1048. {
  1049. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  1050. {
  1051. Assembly plugAss;
  1052. try
  1053. {
  1054. plugAss = Assembly.LoadFrom(file);
  1055. }
  1056. catch (FileLoadException ex)
  1057. {
  1058. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  1059. continue;
  1060. }
  1061. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  1062. yield return plugAss;
  1063. }
  1064. }
  1065. // Include composable parts in the Api assembly
  1066. yield return typeof(ApiEntryPoint).Assembly;
  1067. // Include composable parts in the Dashboard assembly
  1068. yield return typeof(DashboardService).Assembly;
  1069. // Include composable parts in the Model assembly
  1070. yield return typeof(SystemInfo).Assembly;
  1071. // Include composable parts in the Common assembly
  1072. yield return typeof(IApplicationHost).Assembly;
  1073. // Include composable parts in the Controller assembly
  1074. yield return typeof(IServerApplicationHost).Assembly;
  1075. // Include composable parts in the Providers assembly
  1076. yield return typeof(ProviderUtils).Assembly;
  1077. // Include composable parts in the Photos assembly
  1078. yield return typeof(PhotoProvider).Assembly;
  1079. // Emby.Server implementations
  1080. yield return typeof(InstallationManager).Assembly;
  1081. // MediaEncoding
  1082. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  1083. // Dlna
  1084. yield return typeof(DlnaEntryPoint).Assembly;
  1085. // Local metadata
  1086. yield return typeof(BoxSetXmlSaver).Assembly;
  1087. // Notifications
  1088. yield return typeof(NotificationManager).Assembly;
  1089. // Xbmc
  1090. yield return typeof(ArtistNfoProvider).Assembly;
  1091. foreach (var i in GetAssembliesWithPartsInternal())
  1092. {
  1093. yield return i;
  1094. }
  1095. }
  1096. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  1097. /// <summary>
  1098. /// Gets the system status.
  1099. /// </summary>
  1100. /// <param name="cancellationToken">The cancellation token.</param>
  1101. /// <returns>SystemInfo.</returns>
  1102. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  1103. {
  1104. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1105. var transcodingTempPath = ConfigurationManager.GetTranscodePath();
  1106. return new SystemInfo
  1107. {
  1108. HasPendingRestart = HasPendingRestart,
  1109. IsShuttingDown = IsShuttingDown,
  1110. Version = ApplicationVersionString,
  1111. WebSocketPortNumber = HttpPort,
  1112. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  1113. Id = SystemId,
  1114. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1115. WebPath = ApplicationPaths.WebPath,
  1116. LogPath = ApplicationPaths.LogDirectoryPath,
  1117. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  1118. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1119. CachePath = ApplicationPaths.CachePath,
  1120. HttpServerPortNumber = HttpPort,
  1121. SupportsHttps = SupportsHttps,
  1122. HttpsPortNumber = HttpsPort,
  1123. OperatingSystem = OperatingSystem.Id.ToString(),
  1124. OperatingSystemDisplayName = OperatingSystem.Name,
  1125. CanSelfRestart = CanSelfRestart,
  1126. CanLaunchWebBrowser = CanLaunchWebBrowser,
  1127. HasUpdateAvailable = HasUpdateAvailable,
  1128. TranscodingTempPath = transcodingTempPath,
  1129. ServerName = FriendlyName,
  1130. LocalAddress = localAddress,
  1131. SupportsLibraryMonitor = true,
  1132. EncoderLocation = MediaEncoder.EncoderLocation,
  1133. SystemArchitecture = RuntimeInformation.OSArchitecture,
  1134. SystemUpdateLevel = SystemUpdateLevel,
  1135. PackageName = StartupOptions.PackageName
  1136. };
  1137. }
  1138. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  1139. => NetworkManager.GetMacAddresses()
  1140. .Select(i => new WakeOnLanInfo(i))
  1141. .ToList();
  1142. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1143. {
  1144. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1145. return new PublicSystemInfo
  1146. {
  1147. Version = ApplicationVersionString,
  1148. ProductName = ApplicationProductName,
  1149. Id = SystemId,
  1150. OperatingSystem = OperatingSystem.Id.ToString(),
  1151. ServerName = FriendlyName,
  1152. LocalAddress = localAddress
  1153. };
  1154. }
  1155. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1156. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1157. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1158. {
  1159. try
  1160. {
  1161. // Return the first matched address, if found, or the first known local address
  1162. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1163. foreach (var address in addresses)
  1164. {
  1165. return GetLocalApiUrl(address);
  1166. }
  1167. return null;
  1168. }
  1169. catch (Exception ex)
  1170. {
  1171. Logger.LogError(ex, "Error getting local Ip address information");
  1172. }
  1173. return null;
  1174. }
  1175. /// <summary>
  1176. /// Removes the scope id from IPv6 addresses.
  1177. /// </summary>
  1178. /// <param name="address">The IPv6 address.</param>
  1179. /// <returns>The IPv6 address without the scope id.</returns>
  1180. private string RemoveScopeId(string address)
  1181. {
  1182. var index = address.IndexOf('%');
  1183. if (index == -1)
  1184. {
  1185. return address;
  1186. }
  1187. return address.Substring(0, index);
  1188. }
  1189. public string GetLocalApiUrl(IPAddress ipAddress)
  1190. {
  1191. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1192. {
  1193. var str = RemoveScopeId(ipAddress.ToString());
  1194. return GetLocalApiUrl("[" + str + "]");
  1195. }
  1196. return GetLocalApiUrl(ipAddress.ToString());
  1197. }
  1198. public string GetLocalApiUrl(string host)
  1199. {
  1200. if (EnableHttps)
  1201. {
  1202. return string.Format("https://{0}:{1}",
  1203. host,
  1204. HttpsPort.ToString(CultureInfo.InvariantCulture));
  1205. }
  1206. return string.Format("http://{0}:{1}",
  1207. host,
  1208. HttpPort.ToString(CultureInfo.InvariantCulture));
  1209. }
  1210. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1211. {
  1212. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1213. }
  1214. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1215. {
  1216. var addresses = ServerConfigurationManager
  1217. .Configuration
  1218. .LocalNetworkAddresses
  1219. .Select(NormalizeConfiguredLocalAddress)
  1220. .Where(i => i != null)
  1221. .ToList();
  1222. if (addresses.Count == 0)
  1223. {
  1224. addresses.AddRange(NetworkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1225. }
  1226. var resultList = new List<IPAddress>();
  1227. foreach (var address in addresses)
  1228. {
  1229. if (!allowLoopback)
  1230. {
  1231. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1232. {
  1233. continue;
  1234. }
  1235. }
  1236. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1237. if (valid)
  1238. {
  1239. resultList.Add(address);
  1240. if (limit > 0 && resultList.Count >= limit)
  1241. {
  1242. return resultList;
  1243. }
  1244. }
  1245. }
  1246. return resultList;
  1247. }
  1248. public IPAddress NormalizeConfiguredLocalAddress(string address)
  1249. {
  1250. var index = address.Trim('/').IndexOf('/');
  1251. if (index != -1)
  1252. {
  1253. address = address.Substring(index + 1);
  1254. }
  1255. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1256. {
  1257. return result;
  1258. }
  1259. return null;
  1260. }
  1261. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1262. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1263. {
  1264. if (address.Equals(IPAddress.Loopback)
  1265. || address.Equals(IPAddress.IPv6Loopback))
  1266. {
  1267. return true;
  1268. }
  1269. var apiUrl = GetLocalApiUrl(address);
  1270. apiUrl += "/system/ping";
  1271. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1272. {
  1273. return cachedResult;
  1274. }
  1275. try
  1276. {
  1277. using (var response = await HttpClient.SendAsync(
  1278. new HttpRequestOptions
  1279. {
  1280. Url = apiUrl,
  1281. LogErrorResponseBody = false,
  1282. BufferContent = false,
  1283. CancellationToken = cancellationToken
  1284. }, HttpMethod.Post).ConfigureAwait(false))
  1285. {
  1286. using (var reader = new StreamReader(response.Content))
  1287. {
  1288. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1289. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1290. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1291. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1292. return valid;
  1293. }
  1294. }
  1295. }
  1296. catch (OperationCanceledException)
  1297. {
  1298. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1299. throw;
  1300. }
  1301. catch (Exception ex)
  1302. {
  1303. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1304. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1305. return false;
  1306. }
  1307. }
  1308. public string FriendlyName =>
  1309. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1310. ? Environment.MachineName
  1311. : ServerConfigurationManager.Configuration.ServerName;
  1312. /// <summary>
  1313. /// Shuts down.
  1314. /// </summary>
  1315. public async Task Shutdown()
  1316. {
  1317. if (IsShuttingDown)
  1318. {
  1319. return;
  1320. }
  1321. IsShuttingDown = true;
  1322. try
  1323. {
  1324. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1325. }
  1326. catch (Exception ex)
  1327. {
  1328. Logger.LogError(ex, "Error sending server shutdown notification");
  1329. }
  1330. ShutdownInternal();
  1331. }
  1332. protected abstract void ShutdownInternal();
  1333. public event EventHandler HasUpdateAvailableChanged;
  1334. private bool _hasUpdateAvailable;
  1335. public bool HasUpdateAvailable
  1336. {
  1337. get => _hasUpdateAvailable;
  1338. set
  1339. {
  1340. var fireEvent = value && !_hasUpdateAvailable;
  1341. _hasUpdateAvailable = value;
  1342. if (fireEvent)
  1343. {
  1344. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1345. }
  1346. }
  1347. }
  1348. /// <summary>
  1349. /// Removes the plugin.
  1350. /// </summary>
  1351. /// <param name="plugin">The plugin.</param>
  1352. public void RemovePlugin(IPlugin plugin)
  1353. {
  1354. var list = Plugins.ToList();
  1355. list.Remove(plugin);
  1356. Plugins = list.ToArray();
  1357. }
  1358. /// <summary>
  1359. /// This returns localhost in the case of no external dns, and the hostname if the
  1360. /// dns is prefixed with a valid Uri prefix.
  1361. /// </summary>
  1362. /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
  1363. /// <returns>The hostname in <paramref name="externalDns"/>.</returns>
  1364. private static string GetHostnameFromExternalDns(string externalDns)
  1365. {
  1366. if (string.IsNullOrEmpty(externalDns))
  1367. {
  1368. return "localhost";
  1369. }
  1370. try
  1371. {
  1372. return new Uri(externalDns).Host;
  1373. }
  1374. catch
  1375. {
  1376. return externalDns;
  1377. }
  1378. }
  1379. public virtual void LaunchUrl(string url)
  1380. {
  1381. if (!CanLaunchWebBrowser)
  1382. {
  1383. throw new NotSupportedException();
  1384. }
  1385. var process = ProcessFactory.Create(new ProcessOptions
  1386. {
  1387. FileName = url,
  1388. EnableRaisingEvents = true,
  1389. UseShellExecute = true,
  1390. ErrorDialog = false
  1391. });
  1392. process.Exited += ProcessExited;
  1393. try
  1394. {
  1395. process.Start();
  1396. }
  1397. catch (Exception ex)
  1398. {
  1399. Logger.LogError(ex, "Error launching url: {url}", url);
  1400. throw;
  1401. }
  1402. }
  1403. private static void ProcessExited(object sender, EventArgs e)
  1404. {
  1405. ((IProcess)sender).Dispose();
  1406. }
  1407. public virtual void EnableLoopback(string appName)
  1408. {
  1409. }
  1410. private bool _disposed = false;
  1411. /// <summary>
  1412. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1413. /// </summary>
  1414. public void Dispose()
  1415. {
  1416. Dispose(true);
  1417. GC.SuppressFinalize(this);
  1418. }
  1419. /// <summary>
  1420. /// Releases unmanaged and - optionally - managed resources.
  1421. /// </summary>
  1422. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1423. protected virtual void Dispose(bool dispose)
  1424. {
  1425. if (_disposed)
  1426. {
  1427. return;
  1428. }
  1429. if (dispose)
  1430. {
  1431. var type = GetType();
  1432. Logger.LogInformation("Disposing {Type}", type.Name);
  1433. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1434. _disposableParts.Clear();
  1435. foreach (var part in parts)
  1436. {
  1437. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1438. try
  1439. {
  1440. part.Dispose();
  1441. }
  1442. catch (Exception ex)
  1443. {
  1444. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1445. }
  1446. }
  1447. _userRepository?.Dispose();
  1448. _displayPreferencesRepository.Dispose();
  1449. }
  1450. _userRepository = null;
  1451. _displayPreferencesRepository = null;
  1452. _disposed = true;
  1453. }
  1454. }
  1455. internal class CertificateInfo
  1456. {
  1457. public string Path { get; set; }
  1458. public string Password { get; set; }
  1459. }
  1460. }