ApplicationHost.cs 67 KB

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