ApplicationHost.cs 66 KB

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