ApplicationHost.cs 71 KB

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