ApplicationHost.cs 71 KB

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