ApplicationHost.cs 66 KB

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