ApplicationHost.cs 66 KB

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