ApplicationHost.cs 70 KB

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