ApplicationHost.cs 66 KB

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