ApplicationHost.cs 68 KB

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