2
0

ApplicationHost.cs 67 KB

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