ApplicationHost.cs 66 KB

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