ApplicationHost.cs 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Reflection;
  10. using System.Runtime.InteropServices;
  11. using System.Security.Cryptography.X509Certificates;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. using Emby.Dlna;
  16. using Emby.Dlna.Main;
  17. using Emby.Dlna.Ssdp;
  18. using Emby.Drawing;
  19. using Emby.Notifications;
  20. using Emby.Photos;
  21. using Emby.Server.Implementations.Activity;
  22. using Emby.Server.Implementations.Archiving;
  23. using Emby.Server.Implementations.Channels;
  24. using Emby.Server.Implementations.Collections;
  25. using Emby.Server.Implementations.Configuration;
  26. using Emby.Server.Implementations.Cryptography;
  27. using Emby.Server.Implementations.Data;
  28. using Emby.Server.Implementations.Devices;
  29. using Emby.Server.Implementations.Diagnostics;
  30. using Emby.Server.Implementations.Dto;
  31. using Emby.Server.Implementations.FFMpeg;
  32. using Emby.Server.Implementations.HttpServer;
  33. using Emby.Server.Implementations.HttpServer.Security;
  34. using Emby.Server.Implementations.IO;
  35. using Emby.Server.Implementations.Library;
  36. using Emby.Server.Implementations.LiveTv;
  37. using Emby.Server.Implementations.Localization;
  38. using Emby.Server.Implementations.Net;
  39. using Emby.Server.Implementations.Playlists;
  40. using Emby.Server.Implementations.Reflection;
  41. using Emby.Server.Implementations.ScheduledTasks;
  42. using Emby.Server.Implementations.Security;
  43. using Emby.Server.Implementations.Serialization;
  44. using Emby.Server.Implementations.Session;
  45. using Emby.Server.Implementations.TV;
  46. using Emby.Server.Implementations.Updates;
  47. using Emby.Server.Implementations.Xml;
  48. using MediaBrowser.Api;
  49. using MediaBrowser.Common;
  50. using MediaBrowser.Common.Configuration;
  51. using MediaBrowser.Common.Events;
  52. using MediaBrowser.Common.Extensions;
  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.Extensions;
  91. using MediaBrowser.Model.Globalization;
  92. using MediaBrowser.Model.IO;
  93. using MediaBrowser.Model.MediaInfo;
  94. using MediaBrowser.Model.Net;
  95. using MediaBrowser.Model.Reflection;
  96. using MediaBrowser.Model.Serialization;
  97. using MediaBrowser.Model.Services;
  98. using MediaBrowser.Model.System;
  99. using MediaBrowser.Model.Tasks;
  100. using MediaBrowser.Model.Updates;
  101. using MediaBrowser.Model.Xml;
  102. using MediaBrowser.Providers.Chapters;
  103. using MediaBrowser.Providers.Manager;
  104. using MediaBrowser.Providers.Subtitles;
  105. using MediaBrowser.WebDashboard.Api;
  106. using MediaBrowser.XbmcMetadata.Providers;
  107. using Microsoft.Extensions.Logging;
  108. using ServiceStack;
  109. using ServiceStack.Text.Jsv;
  110. using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate;
  111. namespace Emby.Server.Implementations
  112. {
  113. /// <summary>
  114. /// Class CompositionRoot
  115. /// </summary>
  116. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  117. {
  118. /// <summary>
  119. /// Gets a value indicating whether this instance can self restart.
  120. /// </summary>
  121. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  122. public abstract bool CanSelfRestart { get; }
  123. /// <summary>
  124. /// Gets or sets a value indicating whether this instance can self update.
  125. /// </summary>
  126. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  127. public virtual bool CanSelfUpdate => false;
  128. public virtual bool CanLaunchWebBrowser
  129. {
  130. get
  131. {
  132. if (!Environment.UserInteractive)
  133. {
  134. return false;
  135. }
  136. if (StartupOptions.IsService)
  137. {
  138. return false;
  139. }
  140. if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
  141. {
  142. return true;
  143. }
  144. if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
  145. {
  146. return true;
  147. }
  148. return false;
  149. }
  150. }
  151. /// <summary>
  152. /// Occurs when [has pending restart changed].
  153. /// </summary>
  154. public event EventHandler HasPendingRestartChanged;
  155. /// <summary>
  156. /// Occurs when [application updated].
  157. /// </summary>
  158. public event EventHandler<GenericEventArgs<PackageVersionInfo>> ApplicationUpdated;
  159. /// <summary>
  160. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  161. /// </summary>
  162. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  163. public bool HasPendingRestart { get; private set; }
  164. public bool IsShuttingDown { get; private set; }
  165. /// <summary>
  166. /// Gets or sets the logger.
  167. /// </summary>
  168. /// <value>The logger.</value>
  169. protected ILogger Logger { get; set; }
  170. /// <summary>
  171. /// Gets or sets the plugins.
  172. /// </summary>
  173. /// <value>The plugins.</value>
  174. public IPlugin[] Plugins { get; protected set; }
  175. /// <summary>
  176. /// Gets or sets the logger factory.
  177. /// </summary>
  178. /// <value>The logger factory.</value>
  179. public ILoggerFactory LoggerFactory { get; protected set; }
  180. /// <summary>
  181. /// Gets the application paths.
  182. /// </summary>
  183. /// <value>The application paths.</value>
  184. protected ServerApplicationPaths ApplicationPaths { get; set; }
  185. /// <summary>
  186. /// Gets all concrete types.
  187. /// </summary>
  188. /// <value>All concrete types.</value>
  189. public Tuple<Type, string>[] AllConcreteTypes { get; protected set; }
  190. /// <summary>
  191. /// The disposable parts
  192. /// </summary>
  193. protected readonly List<IDisposable> DisposableParts = new List<IDisposable>();
  194. /// <summary>
  195. /// Gets the configuration manager.
  196. /// </summary>
  197. /// <value>The configuration manager.</value>
  198. protected IConfigurationManager ConfigurationManager { get; set; }
  199. public IFileSystem FileSystemManager { get; set; }
  200. protected IEnvironmentInfo EnvironmentInfo { get; set; }
  201. private IBlurayExaminer BlurayExaminer { get; set; }
  202. public PackageVersionClass SystemUpdateLevel
  203. {
  204. get
  205. {
  206. #if BETA
  207. return PackageVersionClass.Beta;
  208. #endif
  209. return PackageVersionClass.Release;
  210. }
  211. }
  212. public virtual string OperatingSystemDisplayName => EnvironmentInfo.OperatingSystemName;
  213. /// <summary>
  214. /// The container
  215. /// </summary>
  216. protected readonly SimpleInjector.Container Container = new SimpleInjector.Container();
  217. /// <summary>
  218. /// Gets the server configuration manager.
  219. /// </summary>
  220. /// <value>The server configuration manager.</value>
  221. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  222. /// <summary>
  223. /// Gets the configuration manager.
  224. /// </summary>
  225. /// <returns>IConfigurationManager.</returns>
  226. protected IConfigurationManager GetConfigurationManager()
  227. {
  228. return new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager);
  229. }
  230. protected virtual IResourceFileManager CreateResourceFileManager()
  231. {
  232. return new ResourceFileManager(HttpResultFactory, LoggerFactory, FileSystemManager);
  233. }
  234. /// <summary>
  235. /// Gets or sets the user manager.
  236. /// </summary>
  237. /// <value>The user manager.</value>
  238. public IUserManager UserManager { get; set; }
  239. /// <summary>
  240. /// Gets or sets the library manager.
  241. /// </summary>
  242. /// <value>The library manager.</value>
  243. internal ILibraryManager LibraryManager { get; set; }
  244. /// <summary>
  245. /// Gets or sets the directory watchers.
  246. /// </summary>
  247. /// <value>The directory watchers.</value>
  248. private ILibraryMonitor LibraryMonitor { get; set; }
  249. /// <summary>
  250. /// Gets or sets the provider manager.
  251. /// </summary>
  252. /// <value>The provider manager.</value>
  253. private IProviderManager ProviderManager { get; set; }
  254. /// <summary>
  255. /// Gets or sets the HTTP server.
  256. /// </summary>
  257. /// <value>The HTTP server.</value>
  258. private IHttpServer HttpServer { get; set; }
  259. private IDtoService DtoService { get; set; }
  260. public IImageProcessor ImageProcessor { get; set; }
  261. /// <summary>
  262. /// Gets or sets the media encoder.
  263. /// </summary>
  264. /// <value>The media encoder.</value>
  265. private IMediaEncoder MediaEncoder { get; set; }
  266. private ISubtitleEncoder SubtitleEncoder { get; set; }
  267. private ISessionManager SessionManager { get; set; }
  268. private ILiveTvManager LiveTvManager { get; set; }
  269. public LocalizationManager LocalizationManager { get; set; }
  270. private IEncodingManager EncodingManager { get; set; }
  271. private IChannelManager ChannelManager { get; set; }
  272. /// <summary>
  273. /// Gets or sets the user data repository.
  274. /// </summary>
  275. /// <value>The user data repository.</value>
  276. private IUserDataManager UserDataManager { get; set; }
  277. private IUserRepository UserRepository { get; set; }
  278. internal IDisplayPreferencesRepository DisplayPreferencesRepository { get; set; }
  279. internal SqliteItemRepository ItemRepository { get; set; }
  280. private INotificationManager NotificationManager { get; set; }
  281. private ISubtitleManager SubtitleManager { get; set; }
  282. private IChapterManager ChapterManager { get; set; }
  283. private IDeviceManager DeviceManager { get; set; }
  284. internal IUserViewManager UserViewManager { get; set; }
  285. private IAuthenticationRepository AuthenticationRepository { get; set; }
  286. private ITVSeriesManager TVSeriesManager { get; set; }
  287. private ICollectionManager CollectionManager { get; set; }
  288. private IMediaSourceManager MediaSourceManager { get; set; }
  289. private IPlaylistManager PlaylistManager { get; set; }
  290. /// <summary>
  291. /// Gets or sets the installation manager.
  292. /// </summary>
  293. /// <value>The installation manager.</value>
  294. protected IInstallationManager InstallationManager { get; private set; }
  295. /// <summary>
  296. /// Gets or sets the zip client.
  297. /// </summary>
  298. /// <value>The zip client.</value>
  299. protected IZipClient ZipClient { get; private set; }
  300. protected IHttpResultFactory HttpResultFactory { get; private set; }
  301. protected IAuthService AuthService { get; private set; }
  302. public IStartupOptions StartupOptions { get; private set; }
  303. internal IImageEncoder ImageEncoder { get; private set; }
  304. protected IProcessFactory ProcessFactory { get; private set; }
  305. protected ICryptoProvider CryptographyProvider = new CryptographyProvider();
  306. protected readonly IXmlSerializer XmlSerializer;
  307. protected ISocketFactory SocketFactory { get; private set; }
  308. protected ITaskManager TaskManager { get; private set; }
  309. public IHttpClient HttpClient { get; private set; }
  310. protected INetworkManager NetworkManager { get; set; }
  311. public IJsonSerializer JsonSerializer { get; private set; }
  312. protected IIsoManager IsoManager { get; private set; }
  313. /// <summary>
  314. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  315. /// </summary>
  316. public ApplicationHost(ServerApplicationPaths applicationPaths,
  317. ILoggerFactory loggerFactory,
  318. IStartupOptions options,
  319. IFileSystem fileSystem,
  320. IEnvironmentInfo environmentInfo,
  321. IImageEncoder imageEncoder,
  322. INetworkManager networkManager)
  323. {
  324. // hack alert, until common can target .net core
  325. BaseExtensions.CryptographyProvider = CryptographyProvider;
  326. XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory);
  327. NetworkManager = networkManager;
  328. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  329. EnvironmentInfo = environmentInfo;
  330. ApplicationPaths = applicationPaths;
  331. LoggerFactory = loggerFactory;
  332. FileSystemManager = fileSystem;
  333. ConfigurationManager = GetConfigurationManager();
  334. Logger = LoggerFactory.CreateLogger("App");
  335. StartupOptions = options;
  336. ImageEncoder = imageEncoder;
  337. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  338. NetworkManager.NetworkChanged += NetworkManager_NetworkChanged;
  339. }
  340. public string ExpandVirtualPath(string path)
  341. {
  342. var appPaths = ApplicationPaths;
  343. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  344. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  345. }
  346. public string ReverseVirtualPath(string path)
  347. {
  348. var appPaths = ApplicationPaths;
  349. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  350. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  351. }
  352. private string[] GetConfiguredLocalSubnets()
  353. {
  354. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  355. }
  356. private void NetworkManager_NetworkChanged(object sender, EventArgs e)
  357. {
  358. _validAddressResults.Clear();
  359. }
  360. public string ApplicationVersion => typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
  361. /// <summary>
  362. /// Gets the current application user agent
  363. /// </summary>
  364. /// <value>The application user agent.</value>
  365. public string ApplicationUserAgent => Name.Replace(' ','-') + "/" + ApplicationVersion;
  366. private string _productName;
  367. /// <summary>
  368. /// Gets the current application name
  369. /// </summary>
  370. /// <value>The application name.</value>
  371. public string ApplicationProductName => _productName ?? (_productName = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName);
  372. private DeviceId _deviceId;
  373. public string SystemId
  374. {
  375. get
  376. {
  377. if (_deviceId == null)
  378. {
  379. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory, FileSystemManager);
  380. }
  381. return _deviceId.Value;
  382. }
  383. }
  384. /// <summary>
  385. /// Gets the name.
  386. /// </summary>
  387. /// <value>The name.</value>
  388. public string Name => ApplicationProductName;
  389. private static Tuple<Assembly, string> GetAssembly(Type type)
  390. {
  391. var assembly = type.GetTypeInfo().Assembly;
  392. return new Tuple<Assembly, string>(assembly, null);
  393. }
  394. public virtual IStreamHelper CreateStreamHelper()
  395. {
  396. return new StreamHelper();
  397. }
  398. /// <summary>
  399. /// Creates an instance of type and resolves all constructor dependancies
  400. /// </summary>
  401. /// <param name="type">The type.</param>
  402. /// <returns>System.Object.</returns>
  403. public object CreateInstance(Type type)
  404. {
  405. return Container.GetInstance(type);
  406. }
  407. /// <summary>
  408. /// Creates the instance safe.
  409. /// </summary>
  410. /// <param name="typeInfo">The type information.</param>
  411. /// <returns>System.Object.</returns>
  412. protected object CreateInstanceSafe(Tuple<Type, string> typeInfo)
  413. {
  414. var type = typeInfo.Item1;
  415. try
  416. {
  417. return Container.GetInstance(type);
  418. }
  419. catch (Exception ex)
  420. {
  421. Logger.LogError(ex, "Error creating {type}", type.FullName);
  422. // Don't blow up in release mode
  423. return null;
  424. }
  425. }
  426. /// <summary>
  427. /// Registers the specified obj.
  428. /// </summary>
  429. /// <typeparam name="T"></typeparam>
  430. /// <param name="obj">The obj.</param>
  431. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  432. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  433. where T : class
  434. {
  435. Container.RegisterInstance<T>(obj);
  436. if (manageLifetime)
  437. {
  438. var disposable = obj as IDisposable;
  439. if (disposable != null)
  440. {
  441. DisposableParts.Add(disposable);
  442. }
  443. }
  444. }
  445. /// <summary>
  446. /// Registers the single instance.
  447. /// </summary>
  448. /// <typeparam name="T"></typeparam>
  449. /// <param name="func">The func.</param>
  450. protected void RegisterSingleInstance<T>(Func<T> func)
  451. where T : class
  452. {
  453. Container.RegisterSingleton(func);
  454. }
  455. /// <summary>
  456. /// Resolves this instance.
  457. /// </summary>
  458. /// <typeparam name="T"></typeparam>
  459. /// <returns>``0.</returns>
  460. public T Resolve<T>()
  461. {
  462. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  463. }
  464. /// <summary>
  465. /// Resolves this instance.
  466. /// </summary>
  467. /// <typeparam name="T"></typeparam>
  468. /// <returns>``0.</returns>
  469. public T TryResolve<T>()
  470. {
  471. var result = Container.GetRegistration(typeof(T), false);
  472. if (result == null)
  473. {
  474. return default(T);
  475. }
  476. return (T)result.GetInstance();
  477. }
  478. /// <summary>
  479. /// Loads the assembly.
  480. /// </summary>
  481. /// <param name="file">The file.</param>
  482. /// <returns>Assembly.</returns>
  483. protected Tuple<Assembly, string> LoadAssembly(string file)
  484. {
  485. try
  486. {
  487. var assembly = Assembly.Load(File.ReadAllBytes(file));
  488. return new Tuple<Assembly, string>(assembly, file);
  489. }
  490. catch (Exception ex)
  491. {
  492. Logger.LogError(ex, "Error loading assembly {File}", file);
  493. return null;
  494. }
  495. }
  496. /// <summary>
  497. /// Gets the export types.
  498. /// </summary>
  499. /// <typeparam name="T"></typeparam>
  500. /// <returns>IEnumerable{Type}.</returns>
  501. public IEnumerable<Tuple<Type, string>> GetExportTypes<T>()
  502. {
  503. var currentType = typeof(T);
  504. return AllConcreteTypes.Where(i => currentType.IsAssignableFrom(i.Item1));
  505. }
  506. /// <summary>
  507. /// Gets the exports.
  508. /// </summary>
  509. /// <typeparam name="T"></typeparam>
  510. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  511. /// <returns>IEnumerable{``0}.</returns>
  512. public IEnumerable<T> GetExports<T>(bool manageLifetime = true)
  513. {
  514. var parts = GetExportTypes<T>()
  515. .Select(CreateInstanceSafe)
  516. .Where(i => i != null)
  517. .Cast<T>();
  518. if (manageLifetime)
  519. {
  520. lock (DisposableParts)
  521. {
  522. DisposableParts.AddRange(parts.OfType<IDisposable>());
  523. }
  524. }
  525. return parts;
  526. }
  527. public List<Tuple<T, string>> GetExportsWithInfo<T>(bool manageLifetime = true)
  528. {
  529. var parts = GetExportTypes<T>()
  530. .Select(i =>
  531. {
  532. var obj = CreateInstanceSafe(i);
  533. if (obj == null)
  534. {
  535. return null;
  536. }
  537. return new Tuple<T, string>((T)obj, i.Item2);
  538. })
  539. .Where(i => i != null)
  540. .ToList();
  541. if (manageLifetime)
  542. {
  543. lock (DisposableParts)
  544. {
  545. DisposableParts.AddRange(parts.Select(i => i.Item1).OfType<IDisposable>());
  546. }
  547. }
  548. return parts;
  549. }
  550. /// <summary>
  551. /// Runs the startup tasks.
  552. /// </summary>
  553. public async Task RunStartupTasks()
  554. {
  555. Logger.LogInformation("Running startup tasks");
  556. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  557. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  558. MediaEncoder.Init();
  559. //if (string.IsNullOrWhiteSpace(MediaEncoder.EncoderPath))
  560. //{
  561. // if (ServerConfigurationManager.Configuration.IsStartupWizardCompleted)
  562. // {
  563. // ServerConfigurationManager.Configuration.IsStartupWizardCompleted = false;
  564. // ServerConfigurationManager.SaveConfiguration();
  565. // }
  566. //}
  567. Logger.LogInformation("ServerId: {0}", SystemId);
  568. var entryPoints = GetExports<IServerEntryPoint>();
  569. var now = DateTime.UtcNow;
  570. await Task.WhenAll(StartEntryPoints(entryPoints, true));
  571. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:fff} ms", DateTime.Now - now);
  572. Logger.LogInformation("Core startup complete");
  573. HttpServer.GlobalResponse = null;
  574. now = DateTime.UtcNow;
  575. await Task.WhenAll(StartEntryPoints(entryPoints, false));
  576. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:fff} ms", DateTime.Now - now);
  577. }
  578. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  579. {
  580. foreach (var entryPoint in entryPoints)
  581. {
  582. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  583. {
  584. continue;
  585. }
  586. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  587. yield return entryPoint.RunAsync();
  588. }
  589. }
  590. public async Task Init()
  591. {
  592. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  593. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  594. // Safeguard against invalid configuration
  595. if (HttpPort == HttpsPort)
  596. {
  597. HttpPort = ServerConfiguration.DefaultHttpPort;
  598. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  599. }
  600. JsonSerializer = new JsonSerializer(FileSystemManager);
  601. if (Plugins != null)
  602. {
  603. var pluginBuilder = new StringBuilder();
  604. foreach (var plugin in Plugins)
  605. {
  606. pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version));
  607. }
  608. Logger.LogInformation("Plugins: {plugins}", pluginBuilder.ToString());
  609. }
  610. DiscoverTypes();
  611. SetHttpLimit();
  612. await RegisterResources();
  613. FindParts();
  614. }
  615. protected virtual IHttpClient CreateHttpClient()
  616. {
  617. return new HttpClientManager.HttpClientManager(ApplicationPaths, LoggerFactory, FileSystemManager, () => ApplicationUserAgent);
  618. }
  619. public static IStreamHelper StreamHelper { get; set; }
  620. /// <summary>
  621. /// Registers resources that classes will depend on
  622. /// </summary>
  623. protected async Task RegisterResources()
  624. {
  625. RegisterSingleInstance(ConfigurationManager);
  626. RegisterSingleInstance<IApplicationHost>(this);
  627. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  628. RegisterSingleInstance(JsonSerializer);
  629. RegisterSingleInstance(LoggerFactory, false);
  630. RegisterSingleInstance(Logger);
  631. RegisterSingleInstance(EnvironmentInfo);
  632. RegisterSingleInstance(FileSystemManager);
  633. HttpClient = CreateHttpClient();
  634. RegisterSingleInstance(HttpClient);
  635. RegisterSingleInstance(NetworkManager);
  636. IsoManager = new IsoManager();
  637. RegisterSingleInstance(IsoManager);
  638. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory, FileSystemManager);
  639. RegisterSingleInstance(TaskManager);
  640. RegisterSingleInstance(XmlSerializer);
  641. ProcessFactory = new ProcessFactory();
  642. RegisterSingleInstance(ProcessFactory);
  643. var streamHelper = CreateStreamHelper();
  644. ApplicationHost.StreamHelper = streamHelper;
  645. RegisterSingleInstance(streamHelper);
  646. RegisterSingleInstance(CryptographyProvider);
  647. SocketFactory = new SocketFactory();
  648. RegisterSingleInstance(SocketFactory);
  649. InstallationManager = new InstallationManager(LoggerFactory, this, ApplicationPaths, HttpClient, JsonSerializer, ServerConfigurationManager, FileSystemManager, CryptographyProvider, PackageRuntime);
  650. RegisterSingleInstance(InstallationManager);
  651. ZipClient = new ZipClient(FileSystemManager);
  652. RegisterSingleInstance(ZipClient);
  653. HttpResultFactory = new HttpResultFactory(LoggerFactory, FileSystemManager, JsonSerializer, CreateBrotliCompressor());
  654. RegisterSingleInstance(HttpResultFactory);
  655. RegisterSingleInstance<IServerApplicationHost>(this);
  656. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  657. RegisterSingleInstance(ServerConfigurationManager);
  658. IAssemblyInfo assemblyInfo = new AssemblyInfo();
  659. RegisterSingleInstance(assemblyInfo);
  660. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LoggerFactory);
  661. await LocalizationManager.LoadAll();
  662. RegisterSingleInstance<ILocalizationManager>(LocalizationManager);
  663. BlurayExaminer = new BdInfoExaminer(FileSystemManager);
  664. RegisterSingleInstance(BlurayExaminer);
  665. RegisterSingleInstance<IXmlReaderSettingsFactory>(new XmlReaderSettingsFactory());
  666. UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
  667. RegisterSingleInstance(UserDataManager);
  668. UserRepository = GetUserRepository();
  669. // This is only needed for disposal purposes. If removing this, make sure to have the manager handle disposing it
  670. RegisterSingleInstance(UserRepository);
  671. var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory, JsonSerializer, ApplicationPaths, FileSystemManager);
  672. DisplayPreferencesRepository = displayPreferencesRepo;
  673. RegisterSingleInstance(DisplayPreferencesRepository);
  674. ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory, assemblyInfo);
  675. RegisterSingleInstance<IItemRepository>(ItemRepository);
  676. AuthenticationRepository = GetAuthenticationRepository();
  677. RegisterSingleInstance(AuthenticationRepository);
  678. UserManager = new UserManager(LoggerFactory, ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager, CryptographyProvider);
  679. RegisterSingleInstance(UserManager);
  680. LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
  681. RegisterSingleInstance(LibraryManager);
  682. // TODO wtaylor: investigate use of second music manager
  683. var musicManager = new MusicManager(LibraryManager);
  684. RegisterSingleInstance<IMusicManager>(new MusicManager(LibraryManager));
  685. LibraryMonitor = new LibraryMonitor(LoggerFactory, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager, EnvironmentInfo);
  686. RegisterSingleInstance(LibraryMonitor);
  687. RegisterSingleInstance<ISearchEngine>(() => new SearchEngine(LoggerFactory, LibraryManager, UserManager));
  688. CertificateInfo = GetCertificateInfo(true);
  689. Certificate = GetCertificate(CertificateInfo);
  690. HttpServer = new HttpListenerHost(this,
  691. LoggerFactory,
  692. ServerConfigurationManager,
  693. "web/index.html",
  694. NetworkManager,
  695. JsonSerializer,
  696. XmlSerializer,
  697. GetParseFn);
  698. HttpServer.GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
  699. RegisterSingleInstance(HttpServer);
  700. ImageProcessor = GetImageProcessor();
  701. RegisterSingleInstance(ImageProcessor);
  702. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  703. RegisterSingleInstance(TVSeriesManager);
  704. var encryptionManager = new EncryptionManager();
  705. RegisterSingleInstance<IEncryptionManager>(encryptionManager);
  706. DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LoggerFactory, NetworkManager);
  707. RegisterSingleInstance(DeviceManager);
  708. MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, () => MediaEncoder);
  709. RegisterSingleInstance(MediaSourceManager);
  710. SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
  711. RegisterSingleInstance(SubtitleManager);
  712. ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
  713. RegisterSingleInstance(ProviderManager);
  714. DtoService = new DtoService(LoggerFactory, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, this, () => DeviceManager, () => MediaSourceManager, () => LiveTvManager);
  715. RegisterSingleInstance(DtoService);
  716. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager);
  717. RegisterSingleInstance(ChannelManager);
  718. SessionManager = new SessionManager(UserDataManager, LoggerFactory, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager);
  719. RegisterSingleInstance(SessionManager);
  720. var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory, JsonSerializer, this, assemblyInfo);
  721. RegisterSingleInstance<IDlnaManager>(dlnaManager);
  722. CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager);
  723. RegisterSingleInstance(CollectionManager);
  724. PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory, UserManager, ProviderManager);
  725. RegisterSingleInstance(PlaylistManager);
  726. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, FileSystemManager, () => ChannelManager);
  727. RegisterSingleInstance(LiveTvManager);
  728. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  729. RegisterSingleInstance(UserViewManager);
  730. NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager);
  731. RegisterSingleInstance(NotificationManager);
  732. RegisterSingleInstance<IDeviceDiscovery>(new DeviceDiscovery(LoggerFactory, ServerConfigurationManager, SocketFactory));
  733. ChapterManager = new ChapterManager(LibraryManager, LoggerFactory, ServerConfigurationManager, ItemRepository);
  734. RegisterSingleInstance(ChapterManager);
  735. RegisterMediaEncoder(assemblyInfo);
  736. EncodingManager = new MediaEncoder.EncodingManager(FileSystemManager, LoggerFactory, MediaEncoder, ChapterManager, LibraryManager);
  737. RegisterSingleInstance(EncodingManager);
  738. var activityLogRepo = GetActivityLogRepository();
  739. RegisterSingleInstance(activityLogRepo);
  740. RegisterSingleInstance<IActivityManager>(new ActivityManager(LoggerFactory, activityLogRepo, UserManager));
  741. var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
  742. RegisterSingleInstance<IAuthorizationContext>(authContext);
  743. RegisterSingleInstance<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  744. AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, SessionManager, NetworkManager);
  745. RegisterSingleInstance(AuthService);
  746. SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory, ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory);
  747. RegisterSingleInstance(SubtitleEncoder);
  748. RegisterSingleInstance(CreateResourceFileManager());
  749. displayPreferencesRepo.Initialize();
  750. var userDataRepo = new SqliteUserDataRepository(LoggerFactory, ApplicationPaths);
  751. SetStaticProperties();
  752. ((UserManager)UserManager).Initialize();
  753. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  754. ItemRepository.Initialize(userDataRepo, UserManager);
  755. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  756. }
  757. protected virtual IBrotliCompressor CreateBrotliCompressor()
  758. {
  759. return null;
  760. }
  761. private static Func<string, object> GetParseFn(Type propertyType)
  762. {
  763. return s => JsvReader.GetParseFn(propertyType)(s);
  764. }
  765. public virtual string PackageRuntime => "netcore";
  766. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, EnvironmentInfo.EnvironmentInfo environmentInfo)
  767. {
  768. // Distinct these to prevent users from reporting problems that aren't actually problems
  769. var commandLineArgs = Environment
  770. .GetCommandLineArgs()
  771. .Distinct();
  772. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  773. logger.LogInformation("Operating system: {OS} {OSVersion}", environmentInfo.OperatingSystemName, environmentInfo.OperatingSystemVersion);
  774. logger.LogInformation("Architecture: {Architecture}", environmentInfo.SystemArchitecture);
  775. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  776. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  777. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  778. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  779. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  780. }
  781. private void SetHttpLimit()
  782. {
  783. try
  784. {
  785. // Increase the max http request limit
  786. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  787. }
  788. catch (Exception ex)
  789. {
  790. Logger.LogError(ex, "Error setting http limit");
  791. }
  792. }
  793. protected virtual bool SupportsDualModeSockets => true;
  794. private X509Certificate GetCertificate(CertificateInfo info)
  795. {
  796. var certificateLocation = info == null ? null : info.Path;
  797. if (string.IsNullOrWhiteSpace(certificateLocation))
  798. {
  799. return null;
  800. }
  801. try
  802. {
  803. if (!File.Exists(certificateLocation))
  804. {
  805. return null;
  806. }
  807. // Don't use an empty string password
  808. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  809. var localCert = new X509Certificate2(certificateLocation, password);
  810. //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  811. if (!localCert.HasPrivateKey)
  812. {
  813. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  814. return null;
  815. }
  816. return localCert;
  817. }
  818. catch (Exception ex)
  819. {
  820. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  821. return null;
  822. }
  823. }
  824. private IImageProcessor GetImageProcessor()
  825. {
  826. return new ImageProcessor(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
  827. }
  828. protected virtual FFMpegInstallInfo GetFfmpegInstallInfo()
  829. {
  830. var info = new FFMpegInstallInfo();
  831. // Windows builds: http://ffmpeg.zeranoe.com/builds/
  832. // Linux builds: http://johnvansickle.com/ffmpeg/
  833. // OS X builds: http://ffmpegmac.net/
  834. // OS X x64: http://www.evermeet.cx/ffmpeg/
  835. if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Linux)
  836. {
  837. info.FFMpegFilename = "ffmpeg";
  838. info.FFProbeFilename = "ffprobe";
  839. info.ArchiveType = "7z";
  840. info.Version = "20170308";
  841. }
  842. else if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
  843. {
  844. info.FFMpegFilename = "ffmpeg.exe";
  845. info.FFProbeFilename = "ffprobe.exe";
  846. info.Version = "20170308";
  847. info.ArchiveType = "7z";
  848. }
  849. else if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
  850. {
  851. info.FFMpegFilename = "ffmpeg";
  852. info.FFProbeFilename = "ffprobe";
  853. info.ArchiveType = "7z";
  854. info.Version = "20170308";
  855. }
  856. return info;
  857. }
  858. protected virtual FFMpegInfo GetFFMpegInfo()
  859. {
  860. return new FFMpegLoader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager, GetFfmpegInstallInfo())
  861. .GetFFMpegInfo(StartupOptions);
  862. }
  863. /// <summary>
  864. /// Registers the media encoder.
  865. /// </summary>
  866. /// <returns>Task.</returns>
  867. private void RegisterMediaEncoder(IAssemblyInfo assemblyInfo)
  868. {
  869. string encoderPath = null;
  870. string probePath = null;
  871. var info = GetFFMpegInfo();
  872. encoderPath = info.EncoderPath;
  873. probePath = info.ProbePath;
  874. var hasExternalEncoder = string.Equals(info.Version, "external", StringComparison.OrdinalIgnoreCase);
  875. var mediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  876. LoggerFactory,
  877. JsonSerializer,
  878. encoderPath,
  879. probePath,
  880. hasExternalEncoder,
  881. ServerConfigurationManager,
  882. FileSystemManager,
  883. LiveTvManager,
  884. IsoManager,
  885. LibraryManager,
  886. ChannelManager,
  887. SessionManager,
  888. () => SubtitleEncoder,
  889. () => MediaSourceManager,
  890. HttpClient,
  891. ZipClient,
  892. ProcessFactory,
  893. 5000);
  894. MediaEncoder = mediaEncoder;
  895. RegisterSingleInstance(MediaEncoder);
  896. }
  897. /// <summary>
  898. /// Gets the user repository.
  899. /// </summary>
  900. /// <returns>Task{IUserRepository}.</returns>
  901. private IUserRepository GetUserRepository()
  902. {
  903. var repo = new SqliteUserRepository(LoggerFactory, ApplicationPaths, JsonSerializer);
  904. repo.Initialize();
  905. return repo;
  906. }
  907. private IAuthenticationRepository GetAuthenticationRepository()
  908. {
  909. var repo = new AuthenticationRepository(LoggerFactory, ServerConfigurationManager);
  910. repo.Initialize();
  911. return repo;
  912. }
  913. private IActivityRepository GetActivityLogRepository()
  914. {
  915. var repo = new ActivityRepository(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager);
  916. repo.Initialize();
  917. return repo;
  918. }
  919. /// <summary>
  920. /// Dirty hacks
  921. /// </summary>
  922. private void SetStaticProperties()
  923. {
  924. ((SqliteItemRepository)ItemRepository).ImageProcessor = ImageProcessor;
  925. // For now there's no real way to inject these properly
  926. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  927. BaseItem.ConfigurationManager = ServerConfigurationManager;
  928. BaseItem.LibraryManager = LibraryManager;
  929. BaseItem.ProviderManager = ProviderManager;
  930. BaseItem.LocalizationManager = LocalizationManager;
  931. BaseItem.ItemRepository = ItemRepository;
  932. User.UserManager = UserManager;
  933. BaseItem.FileSystem = FileSystemManager;
  934. BaseItem.UserDataManager = UserDataManager;
  935. BaseItem.ChannelManager = ChannelManager;
  936. Video.LiveTvManager = LiveTvManager;
  937. Folder.UserViewManager = UserViewManager;
  938. UserView.TVSeriesManager = TVSeriesManager;
  939. UserView.PlaylistManager = PlaylistManager;
  940. UserView.CollectionManager = CollectionManager;
  941. BaseItem.MediaSourceManager = MediaSourceManager;
  942. CollectionFolder.XmlSerializer = XmlSerializer;
  943. CollectionFolder.JsonSerializer = JsonSerializer;
  944. CollectionFolder.ApplicationHost = this;
  945. AuthenticatedAttribute.AuthService = AuthService;
  946. }
  947. /// <summary>
  948. /// Finds the parts.
  949. /// </summary>
  950. protected void FindParts()
  951. {
  952. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  953. {
  954. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  955. ConfigurationManager.SaveConfiguration();
  956. }
  957. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  958. Plugins = GetExportsWithInfo<IPlugin>().Select(LoadPlugin).Where(i => i != null).ToArray();
  959. HttpServer.Init(GetExports<IService>(false), GetExports<IWebSocketListener>());
  960. StartServer();
  961. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  962. GetExports<IItemResolver>(),
  963. GetExports<IIntroProvider>(),
  964. GetExports<IBaseItemComparer>(),
  965. GetExports<ILibraryPostScanTask>());
  966. ProviderManager.AddParts(GetExports<IImageProvider>(),
  967. GetExports<IMetadataService>(),
  968. GetExports<IMetadataProvider>(),
  969. GetExports<IMetadataSaver>(),
  970. GetExports<IExternalId>());
  971. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  972. LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  973. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  974. ChannelManager.AddParts(GetExports<IChannel>());
  975. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  976. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  977. UserManager.AddParts(GetExports<IAuthenticationProvider>());
  978. IsoManager.AddParts(GetExports<IIsoMounter>());
  979. }
  980. private IPlugin LoadPlugin(Tuple<IPlugin, string> info)
  981. {
  982. var plugin = info.Item1;
  983. var assemblyFilePath = info.Item2;
  984. try
  985. {
  986. var assemblyPlugin = plugin as IPluginAssembly;
  987. if (assemblyPlugin != null)
  988. {
  989. var assembly = plugin.GetType().Assembly;
  990. var assemblyName = assembly.GetName();
  991. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  992. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  993. try
  994. {
  995. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  996. if (idAttributes.Length > 0)
  997. {
  998. var attribute = (GuidAttribute)idAttributes[0];
  999. var assemblyId = new Guid(attribute.Value);
  1000. assemblyPlugin.SetId(assemblyId);
  1001. }
  1002. }
  1003. catch (Exception ex)
  1004. {
  1005. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  1006. }
  1007. }
  1008. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  1009. {
  1010. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  1011. }
  1012. }
  1013. catch (Exception ex)
  1014. {
  1015. Logger.LogError(ex, "Error loading plugin {pluginName}", plugin.GetType().FullName);
  1016. return null;
  1017. }
  1018. return plugin;
  1019. }
  1020. /// <summary>
  1021. /// Discovers the types.
  1022. /// </summary>
  1023. protected void DiscoverTypes()
  1024. {
  1025. Logger.LogInformation("Loading assemblies");
  1026. var assemblyInfos = GetComposablePartAssemblies();
  1027. foreach (var assemblyInfo in assemblyInfos)
  1028. {
  1029. var assembly = assemblyInfo.Item1;
  1030. var path = assemblyInfo.Item2;
  1031. if (path == null)
  1032. {
  1033. Logger.LogInformation("Loading {assemblyName}", assembly.FullName);
  1034. }
  1035. else
  1036. {
  1037. Logger.LogInformation("Loading {assemblyName} from {path}", assembly.FullName, path);
  1038. }
  1039. }
  1040. AllConcreteTypes = assemblyInfos
  1041. .SelectMany(GetTypes)
  1042. .Where(info =>
  1043. {
  1044. var t = info.Item1;
  1045. return t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType;
  1046. })
  1047. .ToArray();
  1048. }
  1049. /// <summary>
  1050. /// Gets a list of types within an assembly
  1051. /// This will handle situations that would normally throw an exception - such as a type within the assembly that depends on some other non-existant reference
  1052. /// </summary>
  1053. protected List<Tuple<Type, string>> GetTypes(Tuple<Assembly, string> assemblyInfo)
  1054. {
  1055. if (assemblyInfo == null)
  1056. {
  1057. return new List<Tuple<Type, string>>();
  1058. }
  1059. var assembly = assemblyInfo.Item1;
  1060. try
  1061. {
  1062. // This null checking really shouldn't be needed but adding it due to some
  1063. // unhandled exceptions in mono 5.0 that are a little hard to hunt down
  1064. var types = assembly.GetTypes() ?? new Type[] { };
  1065. return types.Where(t => t != null).Select(i => new Tuple<Type, string>(i, assemblyInfo.Item2)).ToList();
  1066. }
  1067. catch (ReflectionTypeLoadException ex)
  1068. {
  1069. if (ex.LoaderExceptions != null)
  1070. {
  1071. foreach (var loaderException in ex.LoaderExceptions)
  1072. {
  1073. if (loaderException != null)
  1074. {
  1075. Logger.LogError("LoaderException: " + loaderException.Message);
  1076. }
  1077. }
  1078. }
  1079. // If it fails we can still get a list of the Types it was able to resolve
  1080. var types = ex.Types ?? new Type[] { };
  1081. return types.Where(t => t != null).Select(i => new Tuple<Type, string>(i, assemblyInfo.Item2)).ToList();
  1082. }
  1083. catch (Exception ex)
  1084. {
  1085. Logger.LogError(ex, "Error loading types from assembly");
  1086. return new List<Tuple<Type, string>>();
  1087. }
  1088. }
  1089. private CertificateInfo CertificateInfo { get; set; }
  1090. protected X509Certificate Certificate { get; private set; }
  1091. private IEnumerable<string> GetUrlPrefixes()
  1092. {
  1093. var hosts = new[] { "+" };
  1094. return hosts.SelectMany(i =>
  1095. {
  1096. var prefixes = new List<string>
  1097. {
  1098. "http://"+i+":" + HttpPort + "/"
  1099. };
  1100. if (CertificateInfo != null)
  1101. {
  1102. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  1103. }
  1104. return prefixes;
  1105. });
  1106. }
  1107. protected abstract IHttpListener CreateHttpListener();
  1108. /// <summary>
  1109. /// Starts the server.
  1110. /// </summary>
  1111. private void StartServer()
  1112. {
  1113. try
  1114. {
  1115. ((HttpListenerHost)HttpServer).StartServer(GetUrlPrefixes().ToArray(), CreateHttpListener());
  1116. return;
  1117. }
  1118. catch (Exception ex)
  1119. {
  1120. var msg = string.Equals(ex.GetType().Name, "SocketException", StringComparison.OrdinalIgnoreCase)
  1121. ? "The http server is unable to start due to a Socket error. This can occasionally happen when the operating system takes longer than usual to release the IP bindings from the previous session. This can take up to five minutes. Please try waiting or rebooting the system."
  1122. : "Error starting Http Server";
  1123. Logger.LogError(ex, msg);
  1124. if (HttpPort == ServerConfiguration.DefaultHttpPort)
  1125. {
  1126. throw;
  1127. }
  1128. }
  1129. HttpPort = ServerConfiguration.DefaultHttpPort;
  1130. try
  1131. {
  1132. ((HttpListenerHost)HttpServer).StartServer(GetUrlPrefixes().ToArray(), CreateHttpListener());
  1133. }
  1134. catch (Exception ex)
  1135. {
  1136. Logger.LogError(ex, "Error starting http server");
  1137. throw;
  1138. }
  1139. }
  1140. private CertificateInfo GetCertificateInfo(bool generateCertificate)
  1141. {
  1142. if (!string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.CertificatePath))
  1143. {
  1144. // Custom cert
  1145. return new CertificateInfo
  1146. {
  1147. Path = ServerConfigurationManager.Configuration.CertificatePath,
  1148. Password = ServerConfigurationManager.Configuration.CertificatePassword
  1149. };
  1150. }
  1151. // Generate self-signed cert
  1152. var certHost = GetHostnameFromExternalDns(ServerConfigurationManager.Configuration.WanDdns);
  1153. var certPath = Path.Combine(ServerConfigurationManager.ApplicationPaths.ProgramDataPath, "ssl", "cert_" + (certHost + "2").GetMD5().ToString("N") + ".pfx");
  1154. var password = "embycert";
  1155. //if (generateCertificate)
  1156. //{
  1157. // if (!File.Exists(certPath))
  1158. // {
  1159. // FileSystemManager.CreateDirectory(FileSystemManager.GetDirectoryName(certPath));
  1160. // try
  1161. // {
  1162. // CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, password, Logger);
  1163. // }
  1164. // catch (Exception ex)
  1165. // {
  1166. // Logger.LogError(ex, "Error creating ssl cert");
  1167. // return null;
  1168. // }
  1169. // }
  1170. //}
  1171. return new CertificateInfo
  1172. {
  1173. Path = certPath,
  1174. Password = password
  1175. };
  1176. }
  1177. /// <summary>
  1178. /// Called when [configuration updated].
  1179. /// </summary>
  1180. /// <param name="sender">The sender.</param>
  1181. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  1182. protected void OnConfigurationUpdated(object sender, EventArgs e)
  1183. {
  1184. var requiresRestart = false;
  1185. // Don't do anything if these haven't been set yet
  1186. if (HttpPort != 0 && HttpsPort != 0)
  1187. {
  1188. // Need to restart if ports have changed
  1189. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  1190. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  1191. {
  1192. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  1193. {
  1194. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  1195. ServerConfigurationManager.SaveConfiguration();
  1196. requiresRestart = true;
  1197. }
  1198. }
  1199. }
  1200. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  1201. {
  1202. requiresRestart = true;
  1203. }
  1204. var currentCertPath = CertificateInfo == null ? null : CertificateInfo.Path;
  1205. var newCertInfo = GetCertificateInfo(false);
  1206. var newCertPath = newCertInfo == null ? null : newCertInfo.Path;
  1207. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  1208. {
  1209. requiresRestart = true;
  1210. }
  1211. if (requiresRestart)
  1212. {
  1213. Logger.LogInformation("App needs to be restarted due to configuration change.");
  1214. NotifyPendingRestart();
  1215. }
  1216. }
  1217. /// <summary>
  1218. /// Notifies that the kernel that a change has been made that requires a restart
  1219. /// </summary>
  1220. public void NotifyPendingRestart()
  1221. {
  1222. Logger.LogInformation("App needs to be restarted.");
  1223. var changed = !HasPendingRestart;
  1224. HasPendingRestart = true;
  1225. if (changed)
  1226. {
  1227. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  1228. }
  1229. }
  1230. /// <summary>
  1231. /// Restarts this instance.
  1232. /// </summary>
  1233. public void Restart()
  1234. {
  1235. if (!CanSelfRestart)
  1236. {
  1237. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  1238. }
  1239. if (IsShuttingDown)
  1240. {
  1241. return;
  1242. }
  1243. IsShuttingDown = true;
  1244. Task.Run(async () =>
  1245. {
  1246. try
  1247. {
  1248. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  1249. }
  1250. catch (Exception ex)
  1251. {
  1252. Logger.LogError(ex, "Error sending server restart notification");
  1253. }
  1254. Logger.LogInformation("Calling RestartInternal");
  1255. RestartInternal();
  1256. });
  1257. }
  1258. protected abstract void RestartInternal();
  1259. /// <summary>
  1260. /// Gets the composable part assemblies.
  1261. /// </summary>
  1262. /// <returns>IEnumerable{Assembly}.</returns>
  1263. protected List<Tuple<Assembly, string>> GetComposablePartAssemblies()
  1264. {
  1265. var list = GetPluginAssemblies(ApplicationPaths.PluginsPath);
  1266. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  1267. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  1268. // Include composable parts in the Api assembly
  1269. list.Add(GetAssembly(typeof(ApiEntryPoint)));
  1270. // Include composable parts in the Dashboard assembly
  1271. list.Add(GetAssembly(typeof(DashboardService)));
  1272. // Include composable parts in the Model assembly
  1273. list.Add(GetAssembly(typeof(SystemInfo)));
  1274. // Include composable parts in the Common assembly
  1275. list.Add(GetAssembly(typeof(IApplicationHost)));
  1276. // Include composable parts in the Controller assembly
  1277. list.Add(GetAssembly(typeof(IServerApplicationHost)));
  1278. // Include composable parts in the Providers assembly
  1279. list.Add(GetAssembly(typeof(ProviderUtils)));
  1280. // Include composable parts in the Photos assembly
  1281. list.Add(GetAssembly(typeof(PhotoProvider)));
  1282. // Emby.Server implementations
  1283. list.Add(GetAssembly(typeof(InstallationManager)));
  1284. // MediaEncoding
  1285. list.Add(GetAssembly(typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder)));
  1286. // Dlna
  1287. list.Add(GetAssembly(typeof(DlnaEntryPoint)));
  1288. // Local metadata
  1289. list.Add(GetAssembly(typeof(BoxSetXmlSaver)));
  1290. // Notifications
  1291. list.Add(GetAssembly(typeof(NotificationManager)));
  1292. // Xbmc
  1293. list.Add(GetAssembly(typeof(ArtistNfoProvider)));
  1294. list.AddRange(GetAssembliesWithPartsInternal().Select(i => new Tuple<Assembly, string>(i, null)));
  1295. return list.ToList();
  1296. }
  1297. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  1298. private List<Tuple<Assembly, string>> GetPluginAssemblies(string path)
  1299. {
  1300. try
  1301. {
  1302. return FilterAssembliesToLoad(Directory.EnumerateFiles(path, "*.dll", SearchOption.TopDirectoryOnly))
  1303. .Select(LoadAssembly)
  1304. .Where(a => a != null)
  1305. .ToList();
  1306. }
  1307. catch (DirectoryNotFoundException)
  1308. {
  1309. return new List<Tuple<Assembly, string>>();
  1310. }
  1311. }
  1312. private IEnumerable<string> FilterAssembliesToLoad(IEnumerable<string> paths)
  1313. {
  1314. var exclude = new[]
  1315. {
  1316. "mbplus.dll",
  1317. "mbintros.dll",
  1318. "embytv.dll",
  1319. "Messenger.dll",
  1320. "Messages.dll",
  1321. "MediaBrowser.Plugins.TvMazeProvider.dll",
  1322. "MBBookshelf.dll",
  1323. "MediaBrowser.Channels.Adult.YouJizz.dll",
  1324. "MediaBrowser.Channels.Vine-co.dll",
  1325. "MediaBrowser.Plugins.Vimeo.dll",
  1326. "MediaBrowser.Channels.Vevo.dll",
  1327. "MediaBrowser.Plugins.Twitch.dll",
  1328. "MediaBrowser.Channels.SvtPlay.dll",
  1329. "MediaBrowser.Plugins.SoundCloud.dll",
  1330. "MediaBrowser.Plugins.SnesBox.dll",
  1331. "MediaBrowser.Plugins.RottenTomatoes.dll",
  1332. "MediaBrowser.Plugins.Revision3.dll",
  1333. "MediaBrowser.Plugins.NesBox.dll",
  1334. "MBChapters.dll",
  1335. "MediaBrowser.Channels.LeagueOfLegends.dll",
  1336. "MediaBrowser.Plugins.ADEProvider.dll",
  1337. "MediaBrowser.Channels.BallStreams.dll",
  1338. "MediaBrowser.Channels.Adult.Beeg.dll",
  1339. "ChannelDownloader.dll",
  1340. "Hamstercat.Emby.EmbyBands.dll",
  1341. "EmbyTV.dll",
  1342. "MediaBrowser.Channels.HitboxTV.dll",
  1343. "MediaBrowser.Channels.HockeyStreams.dll",
  1344. "MediaBrowser.Plugins.ITV.dll",
  1345. "MediaBrowser.Plugins.Lastfm.dll",
  1346. "ServerRestart.dll",
  1347. "MediaBrowser.Plugins.NotifyMyAndroidNotifications.dll",
  1348. "MetadataViewer.dll"
  1349. };
  1350. var minRequiredVersions = new Dictionary<string, Version>(StringComparer.OrdinalIgnoreCase)
  1351. {
  1352. { "moviethemesongs.dll", new Version(1, 6) },
  1353. { "themesongs.dll", new Version(1, 2) }
  1354. };
  1355. return paths.Where(path =>
  1356. {
  1357. var filename = Path.GetFileName(path);
  1358. if (exclude.Contains(filename ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  1359. {
  1360. return false;
  1361. }
  1362. if (minRequiredVersions.TryGetValue(filename, out Version minRequiredVersion))
  1363. {
  1364. try
  1365. {
  1366. var version = Version.Parse(FileVersionInfo.GetVersionInfo(path).FileVersion);
  1367. if (version < minRequiredVersion)
  1368. {
  1369. Logger.LogInformation("Not loading {filename} {version} because the minimum supported version is {minRequiredVersion}. Please update to the newer version", filename, version, minRequiredVersion);
  1370. return false;
  1371. }
  1372. }
  1373. catch (Exception ex)
  1374. {
  1375. Logger.LogError(ex, "Error getting version number from {path}", path);
  1376. return false;
  1377. }
  1378. }
  1379. return true;
  1380. });
  1381. }
  1382. /// <summary>
  1383. /// Gets the system status.
  1384. /// </summary>
  1385. /// <returns>SystemInfo.</returns>
  1386. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  1387. {
  1388. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1389. var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false);
  1390. return new SystemInfo
  1391. {
  1392. HasPendingRestart = HasPendingRestart,
  1393. IsShuttingDown = IsShuttingDown,
  1394. Version = ApplicationVersion,
  1395. ProductName = ApplicationProductName,
  1396. WebSocketPortNumber = HttpPort,
  1397. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  1398. Id = SystemId,
  1399. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1400. LogPath = ApplicationPaths.LogDirectoryPath,
  1401. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  1402. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1403. CachePath = ApplicationPaths.CachePath,
  1404. HttpServerPortNumber = HttpPort,
  1405. SupportsHttps = SupportsHttps,
  1406. HttpsPortNumber = HttpsPort,
  1407. OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(),
  1408. OperatingSystemDisplayName = OperatingSystemDisplayName,
  1409. CanSelfRestart = CanSelfRestart,
  1410. CanSelfUpdate = CanSelfUpdate,
  1411. CanLaunchWebBrowser = CanLaunchWebBrowser,
  1412. WanAddress = wanAddress,
  1413. HasUpdateAvailable = HasUpdateAvailable,
  1414. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  1415. ServerName = FriendlyName,
  1416. LocalAddress = localAddress,
  1417. SupportsLibraryMonitor = true,
  1418. EncoderLocationType = MediaEncoder.EncoderLocationType,
  1419. SystemArchitecture = EnvironmentInfo.SystemArchitecture,
  1420. SystemUpdateLevel = SystemUpdateLevel,
  1421. PackageName = StartupOptions.PackageName
  1422. };
  1423. }
  1424. public WakeOnLanInfo[] GetWakeOnLanInfo()
  1425. {
  1426. return NetworkManager.GetMacAddresses()
  1427. .Select(i => new WakeOnLanInfo
  1428. {
  1429. MacAddress = i
  1430. })
  1431. .ToArray();
  1432. }
  1433. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1434. {
  1435. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1436. var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false);
  1437. return new PublicSystemInfo
  1438. {
  1439. Version = ApplicationVersion,
  1440. Id = SystemId,
  1441. OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(),
  1442. WanAddress = wanAddress,
  1443. ServerName = FriendlyName,
  1444. LocalAddress = localAddress
  1445. };
  1446. }
  1447. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1448. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1449. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1450. {
  1451. try
  1452. {
  1453. // Return the first matched address, if found, or the first known local address
  1454. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1455. foreach (var address in addresses)
  1456. {
  1457. return GetLocalApiUrl(address);
  1458. }
  1459. return null;
  1460. }
  1461. catch (Exception ex)
  1462. {
  1463. Logger.LogError(ex, "Error getting local Ip address information");
  1464. }
  1465. return null;
  1466. }
  1467. public async Task<string> GetWanApiUrl(CancellationToken cancellationToken)
  1468. {
  1469. var url = "http://ipv4.icanhazip.com";
  1470. try
  1471. {
  1472. using (var response = await HttpClient.Get(new HttpRequestOptions
  1473. {
  1474. Url = url,
  1475. LogErrorResponseBody = false,
  1476. LogErrors = false,
  1477. LogRequest = false,
  1478. TimeoutMs = 10000,
  1479. BufferContent = false,
  1480. CancellationToken = cancellationToken
  1481. }))
  1482. {
  1483. return GetLocalApiUrl(response.ReadToEnd().Trim());
  1484. }
  1485. }
  1486. catch (Exception ex)
  1487. {
  1488. Logger.LogError(ex, "Error getting WAN Ip address information");
  1489. }
  1490. return null;
  1491. }
  1492. public string GetLocalApiUrl(IpAddressInfo ipAddress)
  1493. {
  1494. if (ipAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
  1495. {
  1496. return GetLocalApiUrl("[" + ipAddress.Address + "]");
  1497. }
  1498. return GetLocalApiUrl(ipAddress.Address);
  1499. }
  1500. public string GetLocalApiUrl(string host)
  1501. {
  1502. return string.Format("http://{0}:{1}",
  1503. host,
  1504. HttpPort.ToString(CultureInfo.InvariantCulture));
  1505. }
  1506. public Task<List<IpAddressInfo>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1507. {
  1508. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1509. }
  1510. private async Task<List<IpAddressInfo>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1511. {
  1512. var addresses = ServerConfigurationManager
  1513. .Configuration
  1514. .LocalNetworkAddresses
  1515. .Select(NormalizeConfiguredLocalAddress)
  1516. .Where(i => i != null)
  1517. .ToList();
  1518. if (addresses.Count == 0)
  1519. {
  1520. addresses.AddRange(NetworkManager.GetLocalIpAddresses());
  1521. }
  1522. var resultList = new List<IpAddressInfo>();
  1523. foreach (var address in addresses)
  1524. {
  1525. if (!allowLoopback)
  1526. {
  1527. if (address.Equals(IpAddressInfo.Loopback) || address.Equals(IpAddressInfo.IPv6Loopback))
  1528. {
  1529. continue;
  1530. }
  1531. }
  1532. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1533. if (valid)
  1534. {
  1535. resultList.Add(address);
  1536. if (limit > 0 && resultList.Count >= limit)
  1537. {
  1538. return resultList;
  1539. }
  1540. }
  1541. }
  1542. return resultList;
  1543. }
  1544. private IpAddressInfo NormalizeConfiguredLocalAddress(string address)
  1545. {
  1546. var index = address.Trim('/').IndexOf('/');
  1547. if (index != -1)
  1548. {
  1549. address = address.Substring(index + 1);
  1550. }
  1551. if (NetworkManager.TryParseIpAddress(address.Trim('/'), out IpAddressInfo result))
  1552. {
  1553. return result;
  1554. }
  1555. return null;
  1556. }
  1557. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1558. private async Task<bool> IsIpAddressValidAsync(IpAddressInfo address, CancellationToken cancellationToken)
  1559. {
  1560. if (address.Equals(IpAddressInfo.Loopback) ||
  1561. address.Equals(IpAddressInfo.IPv6Loopback))
  1562. {
  1563. return true;
  1564. }
  1565. var apiUrl = GetLocalApiUrl(address);
  1566. apiUrl += "/system/ping";
  1567. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1568. {
  1569. return cachedResult;
  1570. }
  1571. var logPing = false;
  1572. #if DEBUG
  1573. logPing = true;
  1574. #endif
  1575. try
  1576. {
  1577. using (var response = await HttpClient.SendAsync(new HttpRequestOptions
  1578. {
  1579. Url = apiUrl,
  1580. LogErrorResponseBody = false,
  1581. LogErrors = logPing,
  1582. LogRequest = logPing,
  1583. TimeoutMs = 30000,
  1584. BufferContent = false,
  1585. CancellationToken = cancellationToken
  1586. }, "POST").ConfigureAwait(false))
  1587. {
  1588. using (var reader = new StreamReader(response.Content))
  1589. {
  1590. var result = reader.ReadToEnd();
  1591. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1592. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1593. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1594. return valid;
  1595. }
  1596. }
  1597. }
  1598. catch (OperationCanceledException)
  1599. {
  1600. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1601. throw;
  1602. }
  1603. catch (Exception ex)
  1604. {
  1605. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1606. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1607. return false;
  1608. }
  1609. }
  1610. public string FriendlyName =>
  1611. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1612. ? Environment.MachineName
  1613. : ServerConfigurationManager.Configuration.ServerName;
  1614. public int HttpPort { get; private set; }
  1615. public int HttpsPort { get; private set; }
  1616. /// <summary>
  1617. /// Shuts down.
  1618. /// </summary>
  1619. public async Task Shutdown()
  1620. {
  1621. if (IsShuttingDown)
  1622. {
  1623. return;
  1624. }
  1625. IsShuttingDown = true;
  1626. try
  1627. {
  1628. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1629. }
  1630. catch (Exception ex)
  1631. {
  1632. Logger.LogError(ex, "Error sending server shutdown notification");
  1633. }
  1634. ShutdownInternal();
  1635. }
  1636. protected abstract void ShutdownInternal();
  1637. public event EventHandler HasUpdateAvailableChanged;
  1638. private bool _hasUpdateAvailable;
  1639. public bool HasUpdateAvailable
  1640. {
  1641. get => _hasUpdateAvailable;
  1642. set
  1643. {
  1644. var fireEvent = value && !_hasUpdateAvailable;
  1645. _hasUpdateAvailable = value;
  1646. if (fireEvent)
  1647. {
  1648. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1649. }
  1650. }
  1651. }
  1652. /// <summary>
  1653. /// Removes the plugin.
  1654. /// </summary>
  1655. /// <param name="plugin">The plugin.</param>
  1656. public void RemovePlugin(IPlugin plugin)
  1657. {
  1658. var list = Plugins.ToList();
  1659. list.Remove(plugin);
  1660. Plugins = list.ToArray();
  1661. }
  1662. /// <summary>
  1663. /// Updates the application.
  1664. /// </summary>
  1665. /// <param name="package">The package that contains the update</param>
  1666. /// <param name="cancellationToken">The cancellation token.</param>
  1667. /// <param name="progress">The progress.</param>
  1668. public async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  1669. {
  1670. await InstallationManager.InstallPackage(package, false, progress, cancellationToken).ConfigureAwait(false);
  1671. HasUpdateAvailable = false;
  1672. OnApplicationUpdated(package);
  1673. }
  1674. /// <summary>
  1675. /// This returns localhost in the case of no external dns, and the hostname if the
  1676. /// dns is prefixed with a valid Uri prefix.
  1677. /// </summary>
  1678. /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
  1679. /// <returns>The hostname in <paramref name="externalDns"/></returns>
  1680. private static string GetHostnameFromExternalDns(string externalDns)
  1681. {
  1682. if (string.IsNullOrEmpty(externalDns))
  1683. {
  1684. return "localhost";
  1685. }
  1686. try
  1687. {
  1688. return new Uri(externalDns).Host;
  1689. }
  1690. catch
  1691. {
  1692. return externalDns;
  1693. }
  1694. }
  1695. public virtual void LaunchUrl(string url)
  1696. {
  1697. if (!CanLaunchWebBrowser)
  1698. {
  1699. throw new NotSupportedException();
  1700. }
  1701. var process = ProcessFactory.Create(new ProcessOptions
  1702. {
  1703. FileName = url,
  1704. //EnableRaisingEvents = true,
  1705. UseShellExecute = true,
  1706. ErrorDialog = false
  1707. });
  1708. process.Exited += ProcessExited;
  1709. try
  1710. {
  1711. process.Start();
  1712. }
  1713. catch (Exception ex)
  1714. {
  1715. Logger.LogError(ex, "Error launching url: {url}", url);
  1716. throw;
  1717. }
  1718. }
  1719. private static void ProcessExited(object sender, EventArgs e)
  1720. {
  1721. ((IProcess)sender).Dispose();
  1722. }
  1723. public virtual void EnableLoopback(string appName)
  1724. {
  1725. }
  1726. /// <summary>
  1727. /// Called when [application updated].
  1728. /// </summary>
  1729. /// <param name="package">The package.</param>
  1730. protected void OnApplicationUpdated(PackageVersionInfo package)
  1731. {
  1732. Logger.LogInformation("Application has been updated to version {0}", package.versionStr);
  1733. ApplicationUpdated?.Invoke(this, new GenericEventArgs<PackageVersionInfo>
  1734. {
  1735. Argument = package
  1736. });
  1737. NotifyPendingRestart();
  1738. }
  1739. private bool _disposed;
  1740. /// <summary>
  1741. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1742. /// </summary>
  1743. public void Dispose()
  1744. {
  1745. if (!_disposed)
  1746. {
  1747. _disposed = true;
  1748. Dispose(true);
  1749. }
  1750. }
  1751. /// <summary>
  1752. /// Releases unmanaged and - optionally - managed resources.
  1753. /// </summary>
  1754. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1755. protected virtual void Dispose(bool dispose)
  1756. {
  1757. if (dispose)
  1758. {
  1759. var type = GetType();
  1760. Logger.LogInformation("Disposing {Type}", type.Name);
  1761. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1762. DisposableParts.Clear();
  1763. foreach (var part in parts)
  1764. {
  1765. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1766. try
  1767. {
  1768. part.Dispose();
  1769. }
  1770. catch (Exception ex)
  1771. {
  1772. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1773. }
  1774. }
  1775. }
  1776. }
  1777. }
  1778. internal class CertificateInfo
  1779. {
  1780. public string Path { get; set; }
  1781. public string Password { get; set; }
  1782. }
  1783. }