ApplicationHost.cs 70 KB

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