ApplicationHost.cs 70 KB

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