ApplicationHost.cs 67 KB

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