ApplicationHost.cs 71 KB

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