ApplicationHost.cs 67 KB

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