ApplicationHost.cs 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905
  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. public static IStreamHelper StreamHelper { get; set; }
  554. /// <summary>
  555. /// Registers resources that classes will depend on
  556. /// </summary>
  557. protected async Task RegisterResources(IServiceCollection serviceCollection)
  558. {
  559. serviceCollection.AddMemoryCache();
  560. serviceCollection.AddSingleton(ConfigurationManager);
  561. serviceCollection.AddSingleton<IApplicationHost>(this);
  562. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  563. serviceCollection.AddSingleton<IConfiguration>(_configuration);
  564. serviceCollection.AddSingleton(JsonSerializer);
  565. serviceCollection.AddSingleton(LoggerFactory);
  566. serviceCollection.AddLogging();
  567. serviceCollection.AddSingleton(Logger);
  568. serviceCollection.AddSingleton(FileSystemManager);
  569. serviceCollection.AddSingleton<TvDbClientManager>();
  570. HttpClient = new HttpClientManager.HttpClientManager(
  571. ApplicationPaths,
  572. LoggerFactory.CreateLogger<HttpClientManager.HttpClientManager>(),
  573. FileSystemManager,
  574. () => ApplicationUserAgent);
  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. var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory, JsonSerializer, ApplicationPaths, FileSystemManager);
  604. serviceCollection.AddSingleton<IDisplayPreferencesRepository>(displayPreferencesRepo);
  605. ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory, LocalizationManager);
  606. serviceCollection.AddSingleton<IItemRepository>(ItemRepository);
  607. AuthenticationRepository = GetAuthenticationRepository();
  608. serviceCollection.AddSingleton(AuthenticationRepository);
  609. UserRepository = GetUserRepository();
  610. UserManager = new UserManager(LoggerFactory, ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager);
  611. serviceCollection.AddSingleton(UserManager);
  612. LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
  613. serviceCollection.AddSingleton(LibraryManager);
  614. // TODO wtaylor: investigate use of second music manager
  615. var musicManager = new MusicManager(LibraryManager);
  616. serviceCollection.AddSingleton<IMusicManager>(new MusicManager(LibraryManager));
  617. LibraryMonitor = new LibraryMonitor(LoggerFactory, LibraryManager, ServerConfigurationManager, FileSystemManager);
  618. serviceCollection.AddSingleton(LibraryMonitor);
  619. serviceCollection.AddSingleton<ISearchEngine>(new SearchEngine(LoggerFactory, LibraryManager, UserManager));
  620. CertificateInfo = GetCertificateInfo(true);
  621. Certificate = GetCertificate(CertificateInfo);
  622. HttpServer = new HttpListenerHost(
  623. this,
  624. LoggerFactory,
  625. ServerConfigurationManager,
  626. _configuration,
  627. NetworkManager,
  628. JsonSerializer,
  629. XmlSerializer,
  630. CreateHttpListener())
  631. {
  632. GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading")
  633. };
  634. serviceCollection.AddSingleton(HttpServer);
  635. ImageProcessor = GetImageProcessor();
  636. serviceCollection.AddSingleton(ImageProcessor);
  637. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  638. serviceCollection.AddSingleton(TVSeriesManager);
  639. DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager);
  640. serviceCollection.AddSingleton(DeviceManager);
  641. MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, () => MediaEncoder);
  642. serviceCollection.AddSingleton(MediaSourceManager);
  643. SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
  644. serviceCollection.AddSingleton(SubtitleManager);
  645. ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
  646. serviceCollection.AddSingleton(ProviderManager);
  647. DtoService = new DtoService(LoggerFactory, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ProviderManager, this, () => MediaSourceManager, () => LiveTvManager);
  648. serviceCollection.AddSingleton(DtoService);
  649. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, ProviderManager);
  650. serviceCollection.AddSingleton(ChannelManager);
  651. SessionManager = new SessionManager(UserDataManager, LoggerFactory, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, this, AuthenticationRepository, DeviceManager, MediaSourceManager);
  652. serviceCollection.AddSingleton(SessionManager);
  653. serviceCollection.AddSingleton<IDlnaManager>(
  654. new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory, JsonSerializer, this));
  655. CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager);
  656. serviceCollection.AddSingleton(CollectionManager);
  657. PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory, UserManager, ProviderManager);
  658. serviceCollection.AddSingleton(PlaylistManager);
  659. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, FileSystemManager, () => ChannelManager);
  660. serviceCollection.AddSingleton(LiveTvManager);
  661. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  662. serviceCollection.AddSingleton(UserViewManager);
  663. NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager);
  664. serviceCollection.AddSingleton(NotificationManager);
  665. serviceCollection.AddSingleton<IDeviceDiscovery>(
  666. new DeviceDiscovery(LoggerFactory, ServerConfigurationManager, SocketFactory));
  667. ChapterManager = new ChapterManager(LibraryManager, LoggerFactory, ServerConfigurationManager, ItemRepository);
  668. serviceCollection.AddSingleton(ChapterManager);
  669. MediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  670. LoggerFactory,
  671. JsonSerializer,
  672. StartupOptions.FFmpegPath,
  673. ServerConfigurationManager,
  674. FileSystemManager,
  675. () => SubtitleEncoder,
  676. () => MediaSourceManager,
  677. ProcessFactory,
  678. 5000,
  679. LocalizationManager);
  680. serviceCollection.AddSingleton(MediaEncoder);
  681. EncodingManager = new MediaEncoder.EncodingManager(FileSystemManager, LoggerFactory, MediaEncoder, ChapterManager, LibraryManager);
  682. serviceCollection.AddSingleton(EncodingManager);
  683. var activityLogRepo = GetActivityLogRepository();
  684. serviceCollection.AddSingleton(activityLogRepo);
  685. serviceCollection.AddSingleton<IActivityManager>(new ActivityManager(LoggerFactory, activityLogRepo, UserManager));
  686. var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
  687. serviceCollection.AddSingleton<IAuthorizationContext>(authContext);
  688. serviceCollection.AddSingleton<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  689. AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, SessionManager, NetworkManager);
  690. serviceCollection.AddSingleton(AuthService);
  691. SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory, ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory);
  692. serviceCollection.AddSingleton(SubtitleEncoder);
  693. serviceCollection.AddSingleton(typeof(IResourceFileManager), typeof(ResourceFileManager));
  694. displayPreferencesRepo.Initialize();
  695. var userDataRepo = new SqliteUserDataRepository(LoggerFactory, ApplicationPaths);
  696. SetStaticProperties();
  697. ((UserManager)UserManager).Initialize();
  698. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  699. ItemRepository.Initialize(userDataRepo, UserManager);
  700. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  701. _serviceProvider = serviceCollection.BuildServiceProvider();
  702. }
  703. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  704. {
  705. // Distinct these to prevent users from reporting problems that aren't actually problems
  706. var commandLineArgs = Environment
  707. .GetCommandLineArgs()
  708. .Distinct();
  709. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  710. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  711. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  712. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  713. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  714. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  715. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  716. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  717. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  718. }
  719. private X509Certificate2 GetCertificate(CertificateInfo info)
  720. {
  721. var certificateLocation = info?.Path;
  722. if (string.IsNullOrWhiteSpace(certificateLocation))
  723. {
  724. return null;
  725. }
  726. try
  727. {
  728. if (!File.Exists(certificateLocation))
  729. {
  730. return null;
  731. }
  732. // Don't use an empty string password
  733. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  734. var localCert = new X509Certificate2(certificateLocation, password);
  735. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  736. if (!localCert.HasPrivateKey)
  737. {
  738. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  739. return null;
  740. }
  741. return localCert;
  742. }
  743. catch (Exception ex)
  744. {
  745. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  746. return null;
  747. }
  748. }
  749. private IImageProcessor GetImageProcessor()
  750. {
  751. return new ImageProcessor(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
  752. }
  753. /// <summary>
  754. /// Gets the user repository.
  755. /// </summary>
  756. /// <returns>Task{IUserRepository}.</returns>
  757. private IUserRepository GetUserRepository()
  758. {
  759. var repo = new SqliteUserRepository(LoggerFactory, ApplicationPaths, JsonSerializer);
  760. repo.Initialize();
  761. return repo;
  762. }
  763. private IAuthenticationRepository GetAuthenticationRepository()
  764. {
  765. var repo = new AuthenticationRepository(LoggerFactory, ServerConfigurationManager);
  766. repo.Initialize();
  767. return repo;
  768. }
  769. private IActivityRepository GetActivityLogRepository()
  770. {
  771. var repo = new ActivityRepository(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager);
  772. repo.Initialize();
  773. return repo;
  774. }
  775. /// <summary>
  776. /// Dirty hacks
  777. /// </summary>
  778. private void SetStaticProperties()
  779. {
  780. ItemRepository.ImageProcessor = ImageProcessor;
  781. // For now there's no real way to inject these properly
  782. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  783. BaseItem.ConfigurationManager = ServerConfigurationManager;
  784. BaseItem.LibraryManager = LibraryManager;
  785. BaseItem.ProviderManager = ProviderManager;
  786. BaseItem.LocalizationManager = LocalizationManager;
  787. BaseItem.ItemRepository = ItemRepository;
  788. User.UserManager = UserManager;
  789. BaseItem.FileSystem = FileSystemManager;
  790. BaseItem.UserDataManager = UserDataManager;
  791. BaseItem.ChannelManager = ChannelManager;
  792. Video.LiveTvManager = LiveTvManager;
  793. Folder.UserViewManager = UserViewManager;
  794. UserView.TVSeriesManager = TVSeriesManager;
  795. UserView.CollectionManager = CollectionManager;
  796. BaseItem.MediaSourceManager = MediaSourceManager;
  797. CollectionFolder.XmlSerializer = XmlSerializer;
  798. CollectionFolder.JsonSerializer = JsonSerializer;
  799. CollectionFolder.ApplicationHost = this;
  800. AuthenticatedAttribute.AuthService = AuthService;
  801. }
  802. private async void PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> args)
  803. {
  804. string dir = Path.Combine(ApplicationPaths.PluginsPath, args.Argument.name);
  805. var types = Directory.EnumerateFiles(dir, "*.dll", SearchOption.AllDirectories)
  806. .Select(x => Assembly.LoadFrom(x))
  807. .SelectMany(x => x.ExportedTypes)
  808. .Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface && !x.IsGenericType)
  809. .ToList();
  810. types.AddRange(types);
  811. var plugins = types.Where(x => x.IsAssignableFrom(typeof(IPlugin)))
  812. .Select(CreateInstanceSafe)
  813. .Where(x => x != null)
  814. .Cast<IPlugin>()
  815. .Select(LoadPlugin)
  816. .Where(x => x != null)
  817. .ToArray();
  818. int oldLen = _plugins.Length;
  819. Array.Resize<IPlugin>(ref _plugins, _plugins.Length + plugins.Length);
  820. plugins.CopyTo(_plugins, oldLen);
  821. var entries = types.Where(x => x.IsAssignableFrom(typeof(IServerEntryPoint)))
  822. .Select(CreateInstanceSafe)
  823. .Where(x => x != null)
  824. .Cast<IServerEntryPoint>()
  825. .ToList();
  826. await Task.WhenAll(StartEntryPoints(entries, true));
  827. await Task.WhenAll(StartEntryPoints(entries, false));
  828. }
  829. /// <summary>
  830. /// Finds the parts.
  831. /// </summary>
  832. protected void FindParts()
  833. {
  834. InstallationManager = _serviceProvider.GetService<IInstallationManager>();
  835. InstallationManager.PluginInstalled += PluginInstalled;
  836. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  837. {
  838. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  839. ConfigurationManager.SaveConfiguration();
  840. }
  841. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  842. Plugins = GetExports<IPlugin>()
  843. .Select(LoadPlugin)
  844. .Where(i => i != null)
  845. .ToArray();
  846. HttpServer.Init(GetExports<IService>(false), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  847. LibraryManager.AddParts(
  848. GetExports<IResolverIgnoreRule>(),
  849. GetExports<IItemResolver>(),
  850. GetExports<IIntroProvider>(),
  851. GetExports<IBaseItemComparer>(),
  852. GetExports<ILibraryPostScanTask>());
  853. ProviderManager.AddParts(
  854. GetExports<IImageProvider>(),
  855. GetExports<IMetadataService>(),
  856. GetExports<IMetadataProvider>(),
  857. GetExports<IMetadataSaver>(),
  858. GetExports<IExternalId>());
  859. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  860. LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  861. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  862. ChannelManager.AddParts(GetExports<IChannel>());
  863. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  864. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  865. UserManager.AddParts(GetExports<IAuthenticationProvider>(), GetExports<IPasswordResetProvider>());
  866. IsoManager.AddParts(GetExports<IIsoMounter>());
  867. }
  868. private IPlugin LoadPlugin(IPlugin plugin)
  869. {
  870. try
  871. {
  872. if (plugin is IPluginAssembly assemblyPlugin)
  873. {
  874. var assembly = plugin.GetType().Assembly;
  875. var assemblyName = assembly.GetName();
  876. var assemblyFilePath = assembly.Location;
  877. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  878. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  879. try
  880. {
  881. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  882. if (idAttributes.Length > 0)
  883. {
  884. var attribute = (GuidAttribute)idAttributes[0];
  885. var assemblyId = new Guid(attribute.Value);
  886. assemblyPlugin.SetId(assemblyId);
  887. }
  888. }
  889. catch (Exception ex)
  890. {
  891. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  892. }
  893. }
  894. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  895. {
  896. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  897. }
  898. }
  899. catch (Exception ex)
  900. {
  901. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  902. return null;
  903. }
  904. return plugin;
  905. }
  906. /// <summary>
  907. /// Discovers the types.
  908. /// </summary>
  909. protected void DiscoverTypes()
  910. {
  911. Logger.LogInformation("Loading assemblies");
  912. AllConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  913. }
  914. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  915. {
  916. foreach (var ass in assemblies)
  917. {
  918. Type[] exportedTypes;
  919. try
  920. {
  921. exportedTypes = ass.GetExportedTypes();
  922. }
  923. catch (TypeLoadException ex)
  924. {
  925. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  926. continue;
  927. }
  928. foreach (Type type in exportedTypes)
  929. {
  930. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  931. {
  932. yield return type;
  933. }
  934. }
  935. }
  936. }
  937. private CertificateInfo CertificateInfo { get; set; }
  938. protected X509Certificate2 Certificate { get; private set; }
  939. private IEnumerable<string> GetUrlPrefixes()
  940. {
  941. var hosts = new[] { "+" };
  942. return hosts.SelectMany(i =>
  943. {
  944. var prefixes = new List<string>
  945. {
  946. "http://" + i + ":" + HttpPort + "/"
  947. };
  948. if (CertificateInfo != null)
  949. {
  950. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  951. }
  952. return prefixes;
  953. });
  954. }
  955. protected IHttpListener CreateHttpListener() => new WebSocketSharpListener(Logger);
  956. private CertificateInfo GetCertificateInfo(bool generateCertificate)
  957. {
  958. if (!string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.CertificatePath))
  959. {
  960. // Custom cert
  961. return new CertificateInfo
  962. {
  963. Path = ServerConfigurationManager.Configuration.CertificatePath,
  964. Password = ServerConfigurationManager.Configuration.CertificatePassword
  965. };
  966. }
  967. // Generate self-signed cert
  968. var certHost = GetHostnameFromExternalDns(ServerConfigurationManager.Configuration.WanDdns);
  969. var certPath = Path.Combine(ServerConfigurationManager.ApplicationPaths.ProgramDataPath, "ssl", "cert_" + (certHost + "2").GetMD5().ToString("N") + ".pfx");
  970. const string Password = "embycert";
  971. return new CertificateInfo
  972. {
  973. Path = certPath,
  974. Password = Password
  975. };
  976. }
  977. /// <summary>
  978. /// Called when [configuration updated].
  979. /// </summary>
  980. /// <param name="sender">The sender.</param>
  981. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  982. protected void OnConfigurationUpdated(object sender, EventArgs e)
  983. {
  984. var requiresRestart = false;
  985. // Don't do anything if these haven't been set yet
  986. if (HttpPort != 0 && HttpsPort != 0)
  987. {
  988. // Need to restart if ports have changed
  989. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  990. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  991. {
  992. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  993. {
  994. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  995. ServerConfigurationManager.SaveConfiguration();
  996. requiresRestart = true;
  997. }
  998. }
  999. }
  1000. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  1001. {
  1002. requiresRestart = true;
  1003. }
  1004. var currentCertPath = CertificateInfo?.Path;
  1005. var newCertInfo = GetCertificateInfo(false);
  1006. var newCertPath = newCertInfo?.Path;
  1007. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  1008. {
  1009. requiresRestart = true;
  1010. }
  1011. if (requiresRestart)
  1012. {
  1013. Logger.LogInformation("App needs to be restarted due to configuration change.");
  1014. NotifyPendingRestart();
  1015. }
  1016. }
  1017. /// <summary>
  1018. /// Notifies that the kernel that a change has been made that requires a restart
  1019. /// </summary>
  1020. public void NotifyPendingRestart()
  1021. {
  1022. Logger.LogInformation("App needs to be restarted.");
  1023. var changed = !HasPendingRestart;
  1024. HasPendingRestart = true;
  1025. if (changed)
  1026. {
  1027. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  1028. }
  1029. }
  1030. /// <summary>
  1031. /// Restarts this instance.
  1032. /// </summary>
  1033. public void Restart()
  1034. {
  1035. if (!CanSelfRestart)
  1036. {
  1037. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  1038. }
  1039. if (IsShuttingDown)
  1040. {
  1041. return;
  1042. }
  1043. IsShuttingDown = true;
  1044. Task.Run(async () =>
  1045. {
  1046. try
  1047. {
  1048. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  1049. }
  1050. catch (Exception ex)
  1051. {
  1052. Logger.LogError(ex, "Error sending server restart notification");
  1053. }
  1054. Logger.LogInformation("Calling RestartInternal");
  1055. RestartInternal();
  1056. });
  1057. }
  1058. protected abstract void RestartInternal();
  1059. /// <summary>
  1060. /// Gets the composable part assemblies.
  1061. /// </summary>
  1062. /// <returns>IEnumerable{Assembly}.</returns>
  1063. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  1064. {
  1065. if (Directory.Exists(ApplicationPaths.PluginsPath))
  1066. {
  1067. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  1068. {
  1069. Assembly plugAss;
  1070. try
  1071. {
  1072. plugAss = Assembly.LoadFrom(file);
  1073. }
  1074. catch (FileLoadException ex)
  1075. {
  1076. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  1077. continue;
  1078. }
  1079. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  1080. yield return plugAss;
  1081. }
  1082. }
  1083. // Include composable parts in the Api assembly
  1084. yield return typeof(ApiEntryPoint).Assembly;
  1085. // Include composable parts in the Dashboard assembly
  1086. yield return typeof(DashboardService).Assembly;
  1087. // Include composable parts in the Model assembly
  1088. yield return typeof(SystemInfo).Assembly;
  1089. // Include composable parts in the Common assembly
  1090. yield return typeof(IApplicationHost).Assembly;
  1091. // Include composable parts in the Controller assembly
  1092. yield return typeof(IServerApplicationHost).Assembly;
  1093. // Include composable parts in the Providers assembly
  1094. yield return typeof(ProviderUtils).Assembly;
  1095. // Include composable parts in the Photos assembly
  1096. yield return typeof(PhotoProvider).Assembly;
  1097. // Emby.Server implementations
  1098. yield return typeof(InstallationManager).Assembly;
  1099. // MediaEncoding
  1100. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  1101. // Dlna
  1102. yield return typeof(DlnaEntryPoint).Assembly;
  1103. // Local metadata
  1104. yield return typeof(BoxSetXmlSaver).Assembly;
  1105. // Notifications
  1106. yield return typeof(NotificationManager).Assembly;
  1107. // Xbmc
  1108. yield return typeof(ArtistNfoProvider).Assembly;
  1109. foreach (var i in GetAssembliesWithPartsInternal())
  1110. {
  1111. yield return i;
  1112. }
  1113. }
  1114. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  1115. /// <summary>
  1116. /// Gets the system status.
  1117. /// </summary>
  1118. /// <param name="cancellationToken">The cancellation token</param>
  1119. /// <returns>SystemInfo.</returns>
  1120. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  1121. {
  1122. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1123. string wanAddress;
  1124. if (string.IsNullOrEmpty(ServerConfigurationManager.Configuration.WanDdns))
  1125. {
  1126. wanAddress = await GetWanApiUrlFromExternal(cancellationToken).ConfigureAwait(false);
  1127. }
  1128. else
  1129. {
  1130. wanAddress = GetWanApiUrl(ServerConfigurationManager.Configuration.WanDdns);
  1131. }
  1132. return new SystemInfo
  1133. {
  1134. HasPendingRestart = HasPendingRestart,
  1135. IsShuttingDown = IsShuttingDown,
  1136. Version = ApplicationVersion,
  1137. WebSocketPortNumber = HttpPort,
  1138. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  1139. Id = SystemId,
  1140. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1141. WebPath = ApplicationPaths.WebPath,
  1142. LogPath = ApplicationPaths.LogDirectoryPath,
  1143. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  1144. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1145. CachePath = ApplicationPaths.CachePath,
  1146. HttpServerPortNumber = HttpPort,
  1147. SupportsHttps = SupportsHttps,
  1148. HttpsPortNumber = HttpsPort,
  1149. OperatingSystem = OperatingSystem.Id.ToString(),
  1150. OperatingSystemDisplayName = OperatingSystem.Name,
  1151. CanSelfRestart = CanSelfRestart,
  1152. CanLaunchWebBrowser = CanLaunchWebBrowser,
  1153. WanAddress = wanAddress,
  1154. HasUpdateAvailable = HasUpdateAvailable,
  1155. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  1156. ServerName = FriendlyName,
  1157. LocalAddress = localAddress,
  1158. SupportsLibraryMonitor = true,
  1159. EncoderLocation = MediaEncoder.EncoderLocation,
  1160. SystemArchitecture = RuntimeInformation.OSArchitecture,
  1161. SystemUpdateLevel = SystemUpdateLevel,
  1162. PackageName = StartupOptions.PackageName
  1163. };
  1164. }
  1165. public WakeOnLanInfo[] GetWakeOnLanInfo()
  1166. {
  1167. return NetworkManager.GetMacAddresses()
  1168. .Select(i => new WakeOnLanInfo
  1169. {
  1170. MacAddress = i
  1171. })
  1172. .ToArray();
  1173. }
  1174. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1175. {
  1176. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1177. string wanAddress;
  1178. if (string.IsNullOrEmpty(ServerConfigurationManager.Configuration.WanDdns))
  1179. {
  1180. wanAddress = await GetWanApiUrlFromExternal(cancellationToken).ConfigureAwait(false);
  1181. }
  1182. else
  1183. {
  1184. wanAddress = GetWanApiUrl(ServerConfigurationManager.Configuration.WanDdns);
  1185. }
  1186. return new PublicSystemInfo
  1187. {
  1188. Version = ApplicationVersion,
  1189. ProductName = ApplicationProductName,
  1190. Id = SystemId,
  1191. OperatingSystem = OperatingSystem.Id.ToString(),
  1192. WanAddress = wanAddress,
  1193. ServerName = FriendlyName,
  1194. LocalAddress = localAddress
  1195. };
  1196. }
  1197. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1198. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1199. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1200. {
  1201. try
  1202. {
  1203. // Return the first matched address, if found, or the first known local address
  1204. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1205. foreach (var address in addresses)
  1206. {
  1207. return GetLocalApiUrl(address);
  1208. }
  1209. return null;
  1210. }
  1211. catch (Exception ex)
  1212. {
  1213. Logger.LogError(ex, "Error getting local Ip address information");
  1214. }
  1215. return null;
  1216. }
  1217. public async Task<string> GetWanApiUrlFromExternal(CancellationToken cancellationToken)
  1218. {
  1219. const string Url = "http://ipv4.icanhazip.com";
  1220. try
  1221. {
  1222. using (var response = await HttpClient.Get(new HttpRequestOptions
  1223. {
  1224. Url = Url,
  1225. LogErrorResponseBody = false,
  1226. LogErrors = false,
  1227. LogRequest = false,
  1228. BufferContent = false,
  1229. CancellationToken = cancellationToken
  1230. }).ConfigureAwait(false))
  1231. {
  1232. string res = await response.ReadToEndAsync().ConfigureAwait(false);
  1233. return GetWanApiUrl(res.Trim());
  1234. }
  1235. }
  1236. catch (Exception ex)
  1237. {
  1238. Logger.LogError(ex, "Error getting WAN Ip address information");
  1239. }
  1240. return null;
  1241. }
  1242. public string GetLocalApiUrl(IpAddressInfo ipAddress)
  1243. {
  1244. if (ipAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
  1245. {
  1246. return GetLocalApiUrl("[" + ipAddress.Address + "]");
  1247. }
  1248. return GetLocalApiUrl(ipAddress.Address);
  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(IpAddressInfo ipAddress)
  1263. {
  1264. if (ipAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
  1265. {
  1266. return GetWanApiUrl("[" + ipAddress.Address + "]");
  1267. }
  1268. return GetWanApiUrl(ipAddress.Address);
  1269. }
  1270. public string GetWanApiUrl(string host)
  1271. {
  1272. if (EnableHttps)
  1273. {
  1274. return string.Format("https://{0}:{1}",
  1275. host,
  1276. ServerConfigurationManager.Configuration.PublicHttpsPort.ToString(CultureInfo.InvariantCulture));
  1277. }
  1278. return string.Format("http://{0}:{1}",
  1279. host,
  1280. ServerConfigurationManager.Configuration.PublicPort.ToString(CultureInfo.InvariantCulture));
  1281. }
  1282. public Task<List<IpAddressInfo>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1283. {
  1284. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1285. }
  1286. private async Task<List<IpAddressInfo>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1287. {
  1288. var addresses = ServerConfigurationManager
  1289. .Configuration
  1290. .LocalNetworkAddresses
  1291. .Select(NormalizeConfiguredLocalAddress)
  1292. .Where(i => i != null)
  1293. .ToList();
  1294. if (addresses.Count == 0)
  1295. {
  1296. addresses.AddRange(NetworkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1297. }
  1298. var resultList = new List<IpAddressInfo>();
  1299. foreach (var address in addresses)
  1300. {
  1301. if (!allowLoopback)
  1302. {
  1303. if (address.Equals(IpAddressInfo.Loopback) || address.Equals(IpAddressInfo.IPv6Loopback))
  1304. {
  1305. continue;
  1306. }
  1307. }
  1308. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1309. if (valid)
  1310. {
  1311. resultList.Add(address);
  1312. if (limit > 0 && resultList.Count >= limit)
  1313. {
  1314. return resultList;
  1315. }
  1316. }
  1317. }
  1318. return resultList;
  1319. }
  1320. private IpAddressInfo NormalizeConfiguredLocalAddress(string address)
  1321. {
  1322. var index = address.Trim('/').IndexOf('/');
  1323. if (index != -1)
  1324. {
  1325. address = address.Substring(index + 1);
  1326. }
  1327. if (NetworkManager.TryParseIpAddress(address.Trim('/'), out IpAddressInfo result))
  1328. {
  1329. return result;
  1330. }
  1331. return null;
  1332. }
  1333. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1334. private async Task<bool> IsIpAddressValidAsync(IpAddressInfo address, CancellationToken cancellationToken)
  1335. {
  1336. if (address.Equals(IpAddressInfo.Loopback) ||
  1337. address.Equals(IpAddressInfo.IPv6Loopback))
  1338. {
  1339. return true;
  1340. }
  1341. var apiUrl = GetLocalApiUrl(address);
  1342. apiUrl += "/system/ping";
  1343. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1344. {
  1345. return cachedResult;
  1346. }
  1347. #if DEBUG
  1348. const bool LogPing = true;
  1349. #else
  1350. const bool LogPing = false;
  1351. #endif
  1352. try
  1353. {
  1354. using (var response = await HttpClient.SendAsync(
  1355. new HttpRequestOptions
  1356. {
  1357. Url = apiUrl,
  1358. LogErrorResponseBody = false,
  1359. LogErrors = LogPing,
  1360. LogRequest = LogPing,
  1361. BufferContent = false,
  1362. CancellationToken = cancellationToken
  1363. }, HttpMethod.Post).ConfigureAwait(false))
  1364. {
  1365. using (var reader = new StreamReader(response.Content))
  1366. {
  1367. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1368. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1369. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1370. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1371. return valid;
  1372. }
  1373. }
  1374. }
  1375. catch (OperationCanceledException)
  1376. {
  1377. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1378. throw;
  1379. }
  1380. catch (Exception ex)
  1381. {
  1382. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1383. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1384. return false;
  1385. }
  1386. }
  1387. public string FriendlyName =>
  1388. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1389. ? Environment.MachineName
  1390. : ServerConfigurationManager.Configuration.ServerName;
  1391. public int HttpPort { get; private set; }
  1392. public int HttpsPort { get; private set; }
  1393. /// <summary>
  1394. /// Shuts down.
  1395. /// </summary>
  1396. public async Task Shutdown()
  1397. {
  1398. if (IsShuttingDown)
  1399. {
  1400. return;
  1401. }
  1402. IsShuttingDown = true;
  1403. try
  1404. {
  1405. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1406. }
  1407. catch (Exception ex)
  1408. {
  1409. Logger.LogError(ex, "Error sending server shutdown notification");
  1410. }
  1411. ShutdownInternal();
  1412. }
  1413. protected abstract void ShutdownInternal();
  1414. public event EventHandler HasUpdateAvailableChanged;
  1415. private bool _hasUpdateAvailable;
  1416. public bool HasUpdateAvailable
  1417. {
  1418. get => _hasUpdateAvailable;
  1419. set
  1420. {
  1421. var fireEvent = value && !_hasUpdateAvailable;
  1422. _hasUpdateAvailable = value;
  1423. if (fireEvent)
  1424. {
  1425. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1426. }
  1427. }
  1428. }
  1429. /// <summary>
  1430. /// Removes the plugin.
  1431. /// </summary>
  1432. /// <param name="plugin">The plugin.</param>
  1433. public void RemovePlugin(IPlugin plugin)
  1434. {
  1435. var list = Plugins.ToList();
  1436. list.Remove(plugin);
  1437. Plugins = list.ToArray();
  1438. }
  1439. /// <summary>
  1440. /// This returns localhost in the case of no external dns, and the hostname if the
  1441. /// dns is prefixed with a valid Uri prefix.
  1442. /// </summary>
  1443. /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
  1444. /// <returns>The hostname in <paramref name="externalDns"/></returns>
  1445. private static string GetHostnameFromExternalDns(string externalDns)
  1446. {
  1447. if (string.IsNullOrEmpty(externalDns))
  1448. {
  1449. return "localhost";
  1450. }
  1451. try
  1452. {
  1453. return new Uri(externalDns).Host;
  1454. }
  1455. catch
  1456. {
  1457. return externalDns;
  1458. }
  1459. }
  1460. public virtual void LaunchUrl(string url)
  1461. {
  1462. if (!CanLaunchWebBrowser)
  1463. {
  1464. throw new NotSupportedException();
  1465. }
  1466. var process = ProcessFactory.Create(new ProcessOptions
  1467. {
  1468. FileName = url,
  1469. EnableRaisingEvents = true,
  1470. UseShellExecute = true,
  1471. ErrorDialog = false
  1472. });
  1473. process.Exited += ProcessExited;
  1474. try
  1475. {
  1476. process.Start();
  1477. }
  1478. catch (Exception ex)
  1479. {
  1480. Logger.LogError(ex, "Error launching url: {url}", url);
  1481. throw;
  1482. }
  1483. }
  1484. private static void ProcessExited(object sender, EventArgs e)
  1485. {
  1486. ((IProcess)sender).Dispose();
  1487. }
  1488. public virtual void EnableLoopback(string appName)
  1489. {
  1490. }
  1491. private bool _disposed = false;
  1492. /// <summary>
  1493. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1494. /// </summary>
  1495. public void Dispose()
  1496. {
  1497. Dispose(true);
  1498. GC.SuppressFinalize(this);
  1499. }
  1500. /// <summary>
  1501. /// Releases unmanaged and - optionally - managed resources.
  1502. /// </summary>
  1503. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1504. protected virtual void Dispose(bool dispose)
  1505. {
  1506. if (_disposed)
  1507. {
  1508. return;
  1509. }
  1510. if (dispose)
  1511. {
  1512. var type = GetType();
  1513. Logger.LogInformation("Disposing {Type}", type.Name);
  1514. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1515. _disposableParts.Clear();
  1516. foreach (var part in parts)
  1517. {
  1518. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1519. try
  1520. {
  1521. part.Dispose();
  1522. }
  1523. catch (Exception ex)
  1524. {
  1525. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1526. }
  1527. }
  1528. UserRepository.Dispose();
  1529. }
  1530. UserRepository = null;
  1531. _disposed = true;
  1532. }
  1533. }
  1534. internal class CertificateInfo
  1535. {
  1536. public string Path { get; set; }
  1537. public string Password { get; set; }
  1538. }
  1539. }