ApplicationHost.cs 66 KB

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