ApplicationHost.cs 66 KB

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