ApplicationHost.cs 68 KB

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