ApplicationHost.cs 80 KB

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