ApplicationHost.cs 66 KB

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