ApplicationHost.cs 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  1. using Emby.Drawing;
  2. using Emby.Drawing.GDI;
  3. using Emby.Drawing.ImageMagick;
  4. using MediaBrowser.Api;
  5. using MediaBrowser.Common;
  6. using MediaBrowser.Common.Configuration;
  7. using MediaBrowser.Common.Events;
  8. using MediaBrowser.Common.Extensions;
  9. using Emby.Common.Implementations.ScheduledTasks;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Common.Progress;
  12. using MediaBrowser.Controller;
  13. using MediaBrowser.Controller.Channels;
  14. using MediaBrowser.Controller.Chapters;
  15. using MediaBrowser.Controller.Collections;
  16. using MediaBrowser.Controller.Configuration;
  17. using MediaBrowser.Controller.Connect;
  18. using MediaBrowser.Controller.Devices;
  19. using MediaBrowser.Controller.Dlna;
  20. using MediaBrowser.Controller.Drawing;
  21. using MediaBrowser.Controller.Dto;
  22. using MediaBrowser.Controller.Entities;
  23. using MediaBrowser.Controller.FileOrganization;
  24. using MediaBrowser.Controller.Library;
  25. using MediaBrowser.Controller.LiveTv;
  26. using MediaBrowser.Controller.MediaEncoding;
  27. using MediaBrowser.Controller.Net;
  28. using MediaBrowser.Controller.Notifications;
  29. using MediaBrowser.Controller.Persistence;
  30. using MediaBrowser.Controller.Playlists;
  31. using MediaBrowser.Controller.Plugins;
  32. using MediaBrowser.Controller.Providers;
  33. using MediaBrowser.Controller.Resolvers;
  34. using MediaBrowser.Controller.Security;
  35. using MediaBrowser.Controller.Session;
  36. using MediaBrowser.Controller.Sorting;
  37. using MediaBrowser.Controller.Subtitles;
  38. using MediaBrowser.Controller.Sync;
  39. using MediaBrowser.Controller.TV;
  40. using MediaBrowser.LocalMetadata.Savers;
  41. using MediaBrowser.MediaEncoding.BdInfo;
  42. using MediaBrowser.MediaEncoding.Encoder;
  43. using MediaBrowser.MediaEncoding.Subtitles;
  44. using MediaBrowser.Model.Logging;
  45. using MediaBrowser.Model.MediaInfo;
  46. using MediaBrowser.Model.System;
  47. using MediaBrowser.Model.Updates;
  48. using MediaBrowser.Providers.Chapters;
  49. using MediaBrowser.Providers.Manager;
  50. using MediaBrowser.Providers.Subtitles;
  51. using MediaBrowser.Server.Implementations;
  52. using MediaBrowser.Server.Implementations.Devices;
  53. using MediaBrowser.Server.Startup.Common.FFMpeg;
  54. using MediaBrowser.Server.Startup.Common.Migrations;
  55. using MediaBrowser.WebDashboard.Api;
  56. using MediaBrowser.XbmcMetadata.Providers;
  57. using System;
  58. using System.Collections.Concurrent;
  59. using System.Collections.Generic;
  60. using System.Globalization;
  61. using System.IO;
  62. using System.Linq;
  63. using System.Net;
  64. using System.Net.Sockets;
  65. using System.Reflection;
  66. using System.Security.Cryptography.X509Certificates;
  67. using System.Threading;
  68. using System.Threading.Tasks;
  69. using Emby.Common.Implementations;
  70. using Emby.Common.Implementations.Archiving;
  71. using Emby.Common.Implementations.Networking;
  72. using Emby.Common.Implementations.Reflection;
  73. using Emby.Common.Implementations.Serialization;
  74. using Emby.Common.Implementations.TextEncoding;
  75. using Emby.Common.Implementations.Updates;
  76. using Emby.Common.Implementations.Xml;
  77. using Emby.Photos;
  78. using MediaBrowser.Model.IO;
  79. using MediaBrowser.Api.Playback;
  80. using MediaBrowser.Common.Plugins;
  81. using MediaBrowser.Common.Security;
  82. using MediaBrowser.Common.Updates;
  83. using MediaBrowser.Controller.Entities.Audio;
  84. using MediaBrowser.Controller.Entities.Movies;
  85. using MediaBrowser.Controller.Entities.TV;
  86. using Emby.Dlna;
  87. using Emby.Dlna.ConnectionManager;
  88. using Emby.Dlna.ContentDirectory;
  89. using Emby.Dlna.Main;
  90. using Emby.Dlna.MediaReceiverRegistrar;
  91. using Emby.Dlna.Ssdp;
  92. using Emby.Server.Core;
  93. using Emby.Server.Implementations.Activity;
  94. using Emby.Server.Implementations.Channels;
  95. using Emby.Server.Implementations.Collections;
  96. using Emby.Server.Implementations.Connect;
  97. using Emby.Server.Implementations.Devices;
  98. using Emby.Server.Implementations.Dto;
  99. using Emby.Server.Implementations.EntryPoints;
  100. using Emby.Server.Implementations.FileOrganization;
  101. using Emby.Server.Implementations.HttpServer;
  102. using Emby.Server.Implementations.HttpServer.Security;
  103. using Emby.Server.Implementations.Library;
  104. using Emby.Server.Implementations.LiveTv;
  105. using Emby.Server.Implementations.Localization;
  106. using Emby.Server.Implementations.MediaEncoder;
  107. using Emby.Server.Implementations.Notifications;
  108. using Emby.Server.Implementations.Persistence;
  109. using Emby.Server.Implementations.Playlists;
  110. using Emby.Server.Implementations.Security;
  111. using Emby.Server.Implementations.ServerManager;
  112. using Emby.Server.Implementations.Session;
  113. using Emby.Server.Implementations.Social;
  114. using Emby.Server.Implementations.Sync;
  115. using Emby.Server.Implementations.TV;
  116. using Emby.Server.Implementations.Updates;
  117. using MediaBrowser.Model.Activity;
  118. using MediaBrowser.Model.Configuration;
  119. using MediaBrowser.Model.Dlna;
  120. using MediaBrowser.Model.Globalization;
  121. using MediaBrowser.Model.Net;
  122. using MediaBrowser.Model.News;
  123. using MediaBrowser.Model.Reflection;
  124. using MediaBrowser.Model.Serialization;
  125. using MediaBrowser.Model.Services;
  126. using MediaBrowser.Model.Social;
  127. using MediaBrowser.Model.Text;
  128. using MediaBrowser.Model.Xml;
  129. using MediaBrowser.Server.Startup.Common.Activity;
  130. using MediaBrowser.Server.Startup.Common.Configuration;
  131. using MediaBrowser.Server.Startup.Common.Devices;
  132. using MediaBrowser.Server.Startup.Common.IO;
  133. using MediaBrowser.Server.Startup.Common.Notifications;
  134. using MediaBrowser.Server.Startup.Common.Persistence;
  135. using MediaBrowser.Server.Startup.Common.Security;
  136. using MediaBrowser.Server.Startup.Common.Social;
  137. using MediaBrowser.Server.Startup.Common.Sync;
  138. using OpenSubtitlesHandler;
  139. using ServiceStack;
  140. using SocketHttpListener.Primitives;
  141. using StringExtensions = MediaBrowser.Controller.Extensions.StringExtensions;
  142. namespace MediaBrowser.Server.Startup.Common
  143. {
  144. /// <summary>
  145. /// Class CompositionRoot
  146. /// </summary>
  147. public class ApplicationHost : BaseApplicationHost<ServerApplicationPaths>, IServerApplicationHost, IDependencyContainer
  148. {
  149. /// <summary>
  150. /// Gets the server configuration manager.
  151. /// </summary>
  152. /// <value>The server configuration manager.</value>
  153. public IServerConfigurationManager ServerConfigurationManager
  154. {
  155. get { return (IServerConfigurationManager)ConfigurationManager; }
  156. }
  157. /// <summary>
  158. /// Gets the configuration manager.
  159. /// </summary>
  160. /// <returns>IConfigurationManager.</returns>
  161. protected override IConfigurationManager GetConfigurationManager()
  162. {
  163. return new ServerConfigurationManager(ApplicationPaths, LogManager, XmlSerializer, FileSystemManager);
  164. }
  165. /// <summary>
  166. /// Gets or sets the server manager.
  167. /// </summary>
  168. /// <value>The server manager.</value>
  169. private IServerManager ServerManager { get; set; }
  170. /// <summary>
  171. /// Gets or sets the user manager.
  172. /// </summary>
  173. /// <value>The user manager.</value>
  174. public IUserManager UserManager { get; set; }
  175. /// <summary>
  176. /// Gets or sets the library manager.
  177. /// </summary>
  178. /// <value>The library manager.</value>
  179. internal ILibraryManager LibraryManager { get; set; }
  180. /// <summary>
  181. /// Gets or sets the directory watchers.
  182. /// </summary>
  183. /// <value>The directory watchers.</value>
  184. private ILibraryMonitor LibraryMonitor { get; set; }
  185. /// <summary>
  186. /// Gets or sets the provider manager.
  187. /// </summary>
  188. /// <value>The provider manager.</value>
  189. private IProviderManager ProviderManager { get; set; }
  190. /// <summary>
  191. /// Gets or sets the HTTP server.
  192. /// </summary>
  193. /// <value>The HTTP server.</value>
  194. private IHttpServer HttpServer { get; set; }
  195. private IDtoService DtoService { get; set; }
  196. private IImageProcessor ImageProcessor { get; set; }
  197. /// <summary>
  198. /// Gets or sets the media encoder.
  199. /// </summary>
  200. /// <value>The media encoder.</value>
  201. private IMediaEncoder MediaEncoder { get; set; }
  202. private ISubtitleEncoder SubtitleEncoder { get; set; }
  203. private IConnectManager ConnectManager { get; set; }
  204. private ISessionManager SessionManager { get; set; }
  205. private ILiveTvManager LiveTvManager { get; set; }
  206. public ILocalizationManager LocalizationManager { get; set; }
  207. private IEncodingManager EncodingManager { get; set; }
  208. private IChannelManager ChannelManager { get; set; }
  209. private ISyncManager SyncManager { get; set; }
  210. /// <summary>
  211. /// Gets or sets the user data repository.
  212. /// </summary>
  213. /// <value>The user data repository.</value>
  214. private IUserDataManager UserDataManager { get; set; }
  215. private IUserRepository UserRepository { get; set; }
  216. internal IDisplayPreferencesRepository DisplayPreferencesRepository { get; set; }
  217. internal IItemRepository ItemRepository { get; set; }
  218. private INotificationsRepository NotificationsRepository { get; set; }
  219. private IFileOrganizationRepository FileOrganizationRepository { get; set; }
  220. private INotificationManager NotificationManager { get; set; }
  221. private ISubtitleManager SubtitleManager { get; set; }
  222. private IChapterManager ChapterManager { get; set; }
  223. private IDeviceManager DeviceManager { get; set; }
  224. internal IUserViewManager UserViewManager { get; set; }
  225. private IAuthenticationRepository AuthenticationRepository { get; set; }
  226. private ISyncRepository SyncRepository { get; set; }
  227. private ITVSeriesManager TVSeriesManager { get; set; }
  228. private ICollectionManager CollectionManager { get; set; }
  229. private IMediaSourceManager MediaSourceManager { get; set; }
  230. private IPlaylistManager PlaylistManager { get; set; }
  231. /// <summary>
  232. /// Gets or sets the installation manager.
  233. /// </summary>
  234. /// <value>The installation manager.</value>
  235. protected IInstallationManager InstallationManager { get; private set; }
  236. /// <summary>
  237. /// Gets the security manager.
  238. /// </summary>
  239. /// <value>The security manager.</value>
  240. protected ISecurityManager SecurityManager { get; private set; }
  241. /// <summary>
  242. /// Gets or sets the zip client.
  243. /// </summary>
  244. /// <value>The zip client.</value>
  245. protected IZipClient ZipClient { get; private set; }
  246. protected IAuthService AuthService { get; private set; }
  247. private readonly StartupOptions _startupOptions;
  248. private readonly string _releaseAssetFilename;
  249. internal INativeApp NativeApp { get; set; }
  250. internal IPowerManagement PowerManagement { get; private set; }
  251. /// <summary>
  252. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  253. /// </summary>
  254. public ApplicationHost(ServerApplicationPaths applicationPaths,
  255. ILogManager logManager,
  256. StartupOptions options,
  257. IFileSystem fileSystem,
  258. INativeApp nativeApp,
  259. IPowerManagement powerManagement,
  260. string releaseAssetFilename)
  261. : base(applicationPaths, logManager, fileSystem)
  262. {
  263. _startupOptions = options;
  264. _releaseAssetFilename = releaseAssetFilename;
  265. NativeApp = nativeApp;
  266. PowerManagement = powerManagement;
  267. SetBaseExceptionMessage();
  268. }
  269. private Version _version;
  270. /// <summary>
  271. /// Gets the current application version
  272. /// </summary>
  273. /// <value>The application version.</value>
  274. public override Version ApplicationVersion
  275. {
  276. get
  277. {
  278. return _version ?? (_version = NativeApp.GetType().Assembly.GetName().Version);
  279. }
  280. }
  281. public override string OperatingSystemDisplayName
  282. {
  283. get { return NativeApp.Environment.OperatingSystemVersionString; }
  284. }
  285. public override bool IsRunningAsService
  286. {
  287. get { return NativeApp.IsRunningAsService; }
  288. }
  289. public bool SupportsRunningAsService
  290. {
  291. get { return NativeApp.SupportsRunningAsService; }
  292. }
  293. public bool SupportsLibraryMonitor
  294. {
  295. get { return NativeApp.SupportsLibraryMonitor; }
  296. }
  297. /// <summary>
  298. /// Gets the name.
  299. /// </summary>
  300. /// <value>The name.</value>
  301. public override string Name
  302. {
  303. get
  304. {
  305. return "Emby Server";
  306. }
  307. }
  308. /// <summary>
  309. /// Gets a value indicating whether this instance can self restart.
  310. /// </summary>
  311. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  312. public override bool CanSelfRestart
  313. {
  314. get { return NativeApp.CanSelfRestart; }
  315. }
  316. public bool SupportsAutoRunAtStartup
  317. {
  318. get { return NativeApp.SupportsAutoRunAtStartup; }
  319. }
  320. private void SetBaseExceptionMessage()
  321. {
  322. var builder = GetBaseExceptionMessage(ApplicationPaths);
  323. // Skip if plugins haven't been loaded yet
  324. //if (Plugins != null)
  325. //{
  326. // var pluginString = string.Join("|", Plugins.Select(i => i.Name + "-" + i.Version.ToString()).ToArray());
  327. // builder.Insert(0, string.Format("Plugins: {0}{1}", pluginString, Environment.NewLine));
  328. //}
  329. builder.Insert(0, string.Format("Version: {0}{1}", ApplicationVersion, Environment.NewLine));
  330. builder.Insert(0, "*** Error Report ***" + Environment.NewLine);
  331. LogManager.ExceptionMessagePrefix = builder.ToString();
  332. }
  333. /// <summary>
  334. /// Runs the startup tasks.
  335. /// </summary>
  336. public override async Task RunStartupTasks()
  337. {
  338. await PerformPreInitMigrations().ConfigureAwait(false);
  339. if (ServerConfigurationManager.Configuration.MigrationVersion < CleanDatabaseScheduledTask.MigrationVersion &&
  340. ServerConfigurationManager.Configuration.IsStartupWizardCompleted)
  341. {
  342. TaskManager.SuspendTriggers = true;
  343. }
  344. await base.RunStartupTasks().ConfigureAwait(false);
  345. await MediaEncoder.Init().ConfigureAwait(false);
  346. if (string.IsNullOrWhiteSpace(MediaEncoder.EncoderPath))
  347. {
  348. if (ServerConfigurationManager.Configuration.IsStartupWizardCompleted)
  349. {
  350. ServerConfigurationManager.Configuration.IsStartupWizardCompleted = false;
  351. ServerConfigurationManager.SaveConfiguration();
  352. }
  353. }
  354. Logger.Info("ServerId: {0}", SystemId);
  355. Logger.Info("Core startup complete");
  356. HttpServer.GlobalResponse = null;
  357. PerformPostInitMigrations();
  358. Logger.Info("Post-init migrations complete");
  359. foreach (var entryPoint in GetExports<IServerEntryPoint>().ToList())
  360. {
  361. var name = entryPoint.GetType().FullName;
  362. Logger.Info("Starting entry point {0}", name);
  363. var now = DateTime.UtcNow;
  364. try
  365. {
  366. entryPoint.Run();
  367. }
  368. catch (Exception ex)
  369. {
  370. Logger.ErrorException("Error in {0}", ex, name);
  371. }
  372. Logger.Info("Entry point completed: {0}. Duration: {1} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture));
  373. }
  374. Logger.Info("All entry points have started");
  375. LogManager.RemoveConsoleOutput();
  376. }
  377. protected override IMemoryStreamFactory CreateMemoryStreamProvider()
  378. {
  379. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  380. {
  381. return new RecyclableMemoryStreamProvider();
  382. }
  383. return new MemoryStreamProvider();
  384. }
  385. protected override ISystemEvents CreateSystemEvents()
  386. {
  387. return new SystemEvents(LogManager.GetLogger("SystemEvents"));
  388. }
  389. protected override IJsonSerializer CreateJsonSerializer()
  390. {
  391. try
  392. {
  393. // https://github.com/ServiceStack/ServiceStack/blob/master/tests/ServiceStack.WebHost.IntegrationTests/Web.config#L4
  394. Licensing.RegisterLicense("1001-e1JlZjoxMDAxLE5hbWU6VGVzdCBCdXNpbmVzcyxUeXBlOkJ1c2luZXNzLEhhc2g6UHVNTVRPclhvT2ZIbjQ5MG5LZE1mUTd5RUMzQnBucTFEbTE3TDczVEF4QUNMT1FhNXJMOWkzVjFGL2ZkVTE3Q2pDNENqTkQyUktRWmhvUVBhYTBiekJGUUZ3ZE5aZHFDYm9hL3lydGlwUHI5K1JsaTBYbzNsUC85cjVJNHE5QVhldDN6QkE4aTlvdldrdTgyTk1relY2eis2dFFqTThYN2lmc0JveHgycFdjPSxFeHBpcnk6MjAxMy0wMS0wMX0=");
  395. }
  396. catch
  397. {
  398. // Failing under mono
  399. }
  400. var result = new JsonSerializer(FileSystemManager, LogManager.GetLogger("JsonSerializer"));
  401. ServiceStack.Text.JsConfig<LiveTvProgram>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  402. ServiceStack.Text.JsConfig<LiveTvChannel>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  403. ServiceStack.Text.JsConfig<LiveTvVideoRecording>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  404. ServiceStack.Text.JsConfig<LiveTvAudioRecording>.ExcludePropertyNames = new[] { "Artists", "AlbumArtists", "ChannelMediaSources", "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  405. ServiceStack.Text.JsConfig<Series>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  406. ServiceStack.Text.JsConfig<Audio>.ExcludePropertyNames = new[] { "Artists", "AlbumArtists", "ChannelMediaSources", "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  407. ServiceStack.Text.JsConfig<MusicAlbum>.ExcludePropertyNames = new[] { "Artists", "AlbumArtists", "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  408. ServiceStack.Text.JsConfig<MusicArtist>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  409. ServiceStack.Text.JsConfig<MusicGenre>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  410. ServiceStack.Text.JsConfig<MusicVideo>.ExcludePropertyNames = new[] { "Artists", "AlbumArtists", "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  411. ServiceStack.Text.JsConfig<Movie>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  412. ServiceStack.Text.JsConfig<Playlist>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  413. ServiceStack.Text.JsConfig<AudioPodcast>.ExcludePropertyNames = new[] { "Artists", "AlbumArtists", "ChannelMediaSources", "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  414. ServiceStack.Text.JsConfig<Trailer>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  415. ServiceStack.Text.JsConfig<BoxSet>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  416. ServiceStack.Text.JsConfig<Episode>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  417. ServiceStack.Text.JsConfig<Season>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  418. ServiceStack.Text.JsConfig<Book>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  419. ServiceStack.Text.JsConfig<CollectionFolder>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  420. ServiceStack.Text.JsConfig<Folder>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  421. ServiceStack.Text.JsConfig<Game>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  422. ServiceStack.Text.JsConfig<GameGenre>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  423. ServiceStack.Text.JsConfig<GameSystem>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  424. ServiceStack.Text.JsConfig<Genre>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  425. ServiceStack.Text.JsConfig<Person>.ExcludePropertyNames = new[] { "PlaceOfBirth", "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  426. ServiceStack.Text.JsConfig<Photo>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  427. ServiceStack.Text.JsConfig<PhotoAlbum>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  428. ServiceStack.Text.JsConfig<Studio>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  429. ServiceStack.Text.JsConfig<UserRootFolder>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  430. ServiceStack.Text.JsConfig<UserView>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  431. ServiceStack.Text.JsConfig<Video>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  432. ServiceStack.Text.JsConfig<Year>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  433. ServiceStack.Text.JsConfig<Channel>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  434. ServiceStack.Text.JsConfig<AggregateFolder>.ExcludePropertyNames = new[] { "ProviderIds", "ImageInfos", "ProductionLocations", "ThemeSongIds", "ThemeVideoIds", "TotalBitrate", "ShortOverview", "Taglines", "Keywords", "ExtraType" };
  435. return result;
  436. }
  437. public override Task Init(IProgress<double> progress)
  438. {
  439. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  440. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  441. // Safeguard against invalid configuration
  442. if (HttpPort == HttpsPort)
  443. {
  444. HttpPort = ServerConfiguration.DefaultHttpPort;
  445. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  446. }
  447. return base.Init(progress);
  448. }
  449. private async Task PerformPreInitMigrations()
  450. {
  451. var migrations = new List<IVersionMigration>
  452. {
  453. new UpdateLevelMigration(ServerConfigurationManager, this, HttpClient, JsonSerializer, _releaseAssetFilename, Logger)
  454. };
  455. foreach (var task in migrations)
  456. {
  457. try
  458. {
  459. await task.Run().ConfigureAwait(false);
  460. }
  461. catch (Exception ex)
  462. {
  463. Logger.ErrorException("Error running migration", ex);
  464. }
  465. }
  466. }
  467. private void PerformPostInitMigrations()
  468. {
  469. var migrations = new List<IVersionMigration>
  470. {
  471. new DbMigration(ServerConfigurationManager, TaskManager)
  472. };
  473. foreach (var task in migrations)
  474. {
  475. try
  476. {
  477. task.Run();
  478. }
  479. catch (Exception ex)
  480. {
  481. Logger.ErrorException("Error running migration", ex);
  482. }
  483. }
  484. }
  485. /// <summary>
  486. /// Registers resources that classes will depend on
  487. /// </summary>
  488. protected override async Task RegisterResources(IProgress<double> progress)
  489. {
  490. await base.RegisterResources(progress).ConfigureAwait(false);
  491. RegisterSingleInstance(PowerManagement);
  492. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LogManager, FileSystemManager, CryptographyProvider);
  493. RegisterSingleInstance(SecurityManager);
  494. InstallationManager = new InstallationManager(LogManager.GetLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ConfigurationManager, FileSystemManager, CryptographyProvider);
  495. RegisterSingleInstance(InstallationManager);
  496. ZipClient = new ZipClient(FileSystemManager);
  497. RegisterSingleInstance(ZipClient);
  498. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer, XmlSerializer));
  499. RegisterSingleInstance<IServerApplicationHost>(this);
  500. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  501. RegisterSingleInstance(ServerConfigurationManager);
  502. IAssemblyInfo assemblyInfo = new AssemblyInfo();
  503. RegisterSingleInstance<IAssemblyInfo>(assemblyInfo);
  504. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LogManager.GetLogger("LocalizationManager"), assemblyInfo, new TextLocalizer());
  505. StringExtensions.LocalizationManager = LocalizationManager;
  506. RegisterSingleInstance(LocalizationManager);
  507. ITextEncoding textEncoding = new TextEncoding(FileSystemManager);
  508. RegisterSingleInstance(textEncoding);
  509. Utilities.EncodingHelper = textEncoding;
  510. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer(FileSystemManager, textEncoding));
  511. RegisterSingleInstance<IXmlReaderSettingsFactory>(new XmlReaderSettingsFactory());
  512. UserDataManager = new UserDataManager(LogManager, ServerConfigurationManager);
  513. RegisterSingleInstance(UserDataManager);
  514. UserRepository = await GetUserRepository().ConfigureAwait(false);
  515. var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LogManager, JsonSerializer, ApplicationPaths, NativeApp.GetDbConnector(), MemoryStreamProvider);
  516. DisplayPreferencesRepository = displayPreferencesRepo;
  517. RegisterSingleInstance(DisplayPreferencesRepository);
  518. var itemRepo = new SqliteItemRepository(ServerConfigurationManager, JsonSerializer, LogManager, NativeApp.GetDbConnector(), MemoryStreamProvider);
  519. ItemRepository = itemRepo;
  520. RegisterSingleInstance(ItemRepository);
  521. FileOrganizationRepository = await GetFileOrganizationRepository().ConfigureAwait(false);
  522. RegisterSingleInstance(FileOrganizationRepository);
  523. AuthenticationRepository = await GetAuthenticationRepository().ConfigureAwait(false);
  524. RegisterSingleInstance(AuthenticationRepository);
  525. SyncRepository = await GetSyncRepository().ConfigureAwait(false);
  526. RegisterSingleInstance(SyncRepository);
  527. UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, () => ConnectManager, this, JsonSerializer, FileSystemManager, CryptographyProvider, Environment.UserName);
  528. RegisterSingleInstance(UserManager);
  529. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
  530. RegisterSingleInstance(LibraryManager);
  531. var musicManager = new MusicManager(LibraryManager);
  532. RegisterSingleInstance<IMusicManager>(new MusicManager(LibraryManager));
  533. LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager, TimerFactory, SystemEvents, EnvironmentInfo);
  534. RegisterSingleInstance(LibraryMonitor);
  535. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer, MemoryStreamProvider);
  536. RegisterSingleInstance(ProviderManager);
  537. RegisterSingleInstance<ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager));
  538. HttpServer = HttpServerFactory.CreateServer(this, LogManager, ServerConfigurationManager, NetworkManager, MemoryStreamProvider, "Emby", "web/index.html", textEncoding, SocketFactory, CryptographyProvider, JsonSerializer, XmlSerializer, EnvironmentInfo, Certificate);
  539. HttpServer.GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
  540. RegisterSingleInstance(HttpServer, false);
  541. progress.Report(10);
  542. ServerManager = new ServerManager(this, JsonSerializer, LogManager.GetLogger("ServerManager"), ServerConfigurationManager, MemoryStreamProvider, textEncoding);
  543. RegisterSingleInstance(ServerManager);
  544. var innerProgress = new ActionableProgress<double>();
  545. innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15));
  546. ImageProcessor = GetImageProcessor();
  547. RegisterSingleInstance(ImageProcessor);
  548. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  549. RegisterSingleInstance(TVSeriesManager);
  550. SyncManager = new SyncManager(LibraryManager, SyncRepository, ImageProcessor, LogManager.GetLogger("SyncManager"), UserManager, () => DtoService, this, TVSeriesManager, () => MediaEncoder, FileSystemManager, () => SubtitleEncoder, ServerConfigurationManager, UserDataManager, () => MediaSourceManager, JsonSerializer, TaskManager, MemoryStreamProvider);
  551. RegisterSingleInstance(SyncManager);
  552. DtoService = new DtoService(LogManager.GetLogger("DtoService"), LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, SyncManager, this, () => DeviceManager, () => MediaSourceManager, () => LiveTvManager);
  553. RegisterSingleInstance(DtoService);
  554. var encryptionManager = new EncryptionManager();
  555. RegisterSingleInstance<IEncryptionManager>(encryptionManager);
  556. ConnectManager = new ConnectManager(LogManager.GetLogger("ConnectManager"), ApplicationPaths, JsonSerializer, encryptionManager, HttpClient, this, ServerConfigurationManager, UserManager, ProviderManager, SecurityManager, FileSystemManager);
  557. RegisterSingleInstance(ConnectManager);
  558. DeviceManager = new DeviceManager(new DeviceRepository(ApplicationPaths, JsonSerializer, LogManager.GetLogger("DeviceManager"), FileSystemManager), UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LogManager.GetLogger("DeviceManager"), NetworkManager);
  559. RegisterSingleInstance(DeviceManager);
  560. var newsService = new Emby.Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer);
  561. RegisterSingleInstance<INewsService>(newsService);
  562. var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, LogManager.GetLogger("FileOrganizationService"), LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager);
  563. RegisterSingleInstance<IFileOrganizationService>(fileOrganizationService);
  564. progress.Report(15);
  565. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LogManager.GetLogger("ChannelManager"), ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager);
  566. RegisterSingleInstance(ChannelManager);
  567. MediaSourceManager = new MediaSourceManager(ItemRepository, UserManager, LibraryManager, LogManager.GetLogger("MediaSourceManager"), JsonSerializer, FileSystemManager, UserDataManager, TimerFactory);
  568. RegisterSingleInstance(MediaSourceManager);
  569. SessionManager = new SessionManager(UserDataManager, LogManager.GetLogger("SessionManager"), LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager, TimerFactory);
  570. RegisterSingleInstance(SessionManager);
  571. var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer, this, assemblyInfo);
  572. RegisterSingleInstance<IDlnaManager>(dlnaManager);
  573. var connectionManager = new ConnectionManager(dlnaManager, ServerConfigurationManager, LogManager.GetLogger("UpnpConnectionManager"), HttpClient, new XmlReaderSettingsFactory());
  574. RegisterSingleInstance<IConnectionManager>(connectionManager);
  575. CollectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager"), ProviderManager);
  576. RegisterSingleInstance(CollectionManager);
  577. PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager, ProviderManager);
  578. RegisterSingleInstance<IPlaylistManager>(PlaylistManager);
  579. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, ProviderManager, FileSystemManager, SecurityManager);
  580. RegisterSingleInstance(LiveTvManager);
  581. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  582. RegisterSingleInstance(UserViewManager);
  583. var contentDirectory = new ContentDirectory(dlnaManager, UserDataManager, ImageProcessor, LibraryManager, ServerConfigurationManager, UserManager, LogManager.GetLogger("UpnpContentDirectory"), HttpClient, LocalizationManager, ChannelManager, MediaSourceManager, UserViewManager, () => MediaEncoder, new XmlReaderSettingsFactory());
  584. RegisterSingleInstance<IContentDirectory>(contentDirectory);
  585. var mediaRegistrar = new MediaReceiverRegistrar(LogManager.GetLogger("MediaReceiverRegistrar"), HttpClient, ServerConfigurationManager, new XmlReaderSettingsFactory());
  586. RegisterSingleInstance<IMediaReceiverRegistrar>(mediaRegistrar);
  587. NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager);
  588. RegisterSingleInstance(NotificationManager);
  589. SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, MediaSourceManager);
  590. RegisterSingleInstance(SubtitleManager);
  591. RegisterSingleInstance<IDeviceDiscovery>(new DeviceDiscovery(LogManager.GetLogger("IDeviceDiscovery"), ServerConfigurationManager, SocketFactory, TimerFactory));
  592. ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
  593. RegisterSingleInstance(ChapterManager);
  594. await RegisterMediaEncoder(innerProgress).ConfigureAwait(false);
  595. progress.Report(90);
  596. EncodingManager = new EncodingManager(FileSystemManager, Logger, MediaEncoder, ChapterManager, LibraryManager);
  597. RegisterSingleInstance(EncodingManager);
  598. var sharingRepo = new SharingRepository(LogManager, ApplicationPaths, NativeApp.GetDbConnector());
  599. await sharingRepo.Initialize().ConfigureAwait(false);
  600. RegisterSingleInstance<ISharingManager>(new SharingManager(sharingRepo, ServerConfigurationManager, LibraryManager, this));
  601. var activityLogRepo = await GetActivityLogRepository().ConfigureAwait(false);
  602. RegisterSingleInstance(activityLogRepo);
  603. RegisterSingleInstance<IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager));
  604. var authContext = new AuthorizationContext(AuthenticationRepository, ConnectManager);
  605. RegisterSingleInstance<IAuthorizationContext>(authContext);
  606. RegisterSingleInstance<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  607. AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, ConnectManager, SessionManager, DeviceManager);
  608. RegisterSingleInstance<IAuthService>(AuthService);
  609. SubtitleEncoder = new SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, MemoryStreamProvider, ProcessFactory, textEncoding);
  610. RegisterSingleInstance(SubtitleEncoder);
  611. await displayPreferencesRepo.Initialize().ConfigureAwait(false);
  612. var userDataRepo = new SqliteUserDataRepository(LogManager, ApplicationPaths, NativeApp.GetDbConnector());
  613. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  614. await itemRepo.Initialize(userDataRepo).ConfigureAwait(false);
  615. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  616. await ConfigureNotificationsRepository().ConfigureAwait(false);
  617. progress.Report(100);
  618. SetStaticProperties();
  619. await ((UserManager)UserManager).Initialize().ConfigureAwait(false);
  620. }
  621. private ICertificate GetCertificate(string certificateLocation)
  622. {
  623. if (string.IsNullOrWhiteSpace(certificateLocation))
  624. {
  625. return null;
  626. }
  627. try
  628. {
  629. X509Certificate2 localCert = new X509Certificate2(certificateLocation);
  630. //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  631. if (localCert.PrivateKey == null)
  632. {
  633. //throw new FileNotFoundException("Secure requested, no private key included", certificateLocation);
  634. return null;
  635. }
  636. return new Certificate(localCert);
  637. }
  638. catch (Exception ex)
  639. {
  640. Logger.ErrorException("Error loading cert from {0}", ex, certificateLocation);
  641. return null;
  642. }
  643. }
  644. private IImageProcessor GetImageProcessor()
  645. {
  646. var maxConcurrentImageProcesses = Math.Max(Environment.ProcessorCount, 4);
  647. if (_startupOptions.ContainsOption("-imagethreads"))
  648. {
  649. int.TryParse(_startupOptions.GetOption("-imagethreads"), NumberStyles.Any, CultureInfo.InvariantCulture, out maxConcurrentImageProcesses);
  650. }
  651. return new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, GetImageEncoder(), maxConcurrentImageProcesses, () => LibraryManager);
  652. }
  653. private IImageEncoder GetImageEncoder()
  654. {
  655. if (!_startupOptions.ContainsOption("-enablegdi"))
  656. {
  657. try
  658. {
  659. return new ImageMagickEncoder(LogManager.GetLogger("ImageMagick"), ApplicationPaths, HttpClient, FileSystemManager, ServerConfigurationManager);
  660. }
  661. catch
  662. {
  663. Logger.Error("Error loading ImageMagick. Will revert to GDI.");
  664. }
  665. }
  666. try
  667. {
  668. return new GDIImageEncoder(FileSystemManager, LogManager.GetLogger("GDI"));
  669. }
  670. catch
  671. {
  672. Logger.Error("Error loading GDI. Will revert to NullImageEncoder.");
  673. }
  674. return new NullImageEncoder();
  675. }
  676. protected override INetworkManager CreateNetworkManager(ILogger logger)
  677. {
  678. return NativeApp.CreateNetworkManager(logger);
  679. }
  680. /// <summary>
  681. /// Registers the media encoder.
  682. /// </summary>
  683. /// <returns>Task.</returns>
  684. private async Task RegisterMediaEncoder(IProgress<double> progress)
  685. {
  686. string encoderPath = null;
  687. string probePath = null;
  688. var info = await new FFMpegLoader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager, NativeApp.Environment, NativeApp.GetFfmpegInstallInfo())
  689. .GetFFMpegInfo(NativeApp.Environment, _startupOptions, progress).ConfigureAwait(false);
  690. encoderPath = info.EncoderPath;
  691. probePath = info.ProbePath;
  692. var hasExternalEncoder = string.Equals(info.Version, "external", StringComparison.OrdinalIgnoreCase);
  693. var mediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"),
  694. JsonSerializer,
  695. encoderPath,
  696. probePath,
  697. hasExternalEncoder,
  698. ServerConfigurationManager,
  699. FileSystemManager,
  700. LiveTvManager,
  701. IsoManager,
  702. LibraryManager,
  703. ChannelManager,
  704. SessionManager,
  705. () => SubtitleEncoder,
  706. () => MediaSourceManager,
  707. HttpClient,
  708. ZipClient, MemoryStreamProvider,
  709. ProcessFactory,
  710. Environment.Is64BitOperatingSystem ? (Environment.ProcessorCount > 2 ? 14000 : 20000) : 40000,
  711. Environment.OSVersion.Platform == PlatformID.Win32NT);
  712. MediaEncoder = mediaEncoder;
  713. RegisterSingleInstance(MediaEncoder);
  714. }
  715. /// <summary>
  716. /// Gets the user repository.
  717. /// </summary>
  718. /// <returns>Task{IUserRepository}.</returns>
  719. private async Task<IUserRepository> GetUserRepository()
  720. {
  721. var repo = new SqliteUserRepository(LogManager, ApplicationPaths, JsonSerializer, NativeApp.GetDbConnector(), MemoryStreamProvider);
  722. await repo.Initialize().ConfigureAwait(false);
  723. return repo;
  724. }
  725. /// <summary>
  726. /// Gets the file organization repository.
  727. /// </summary>
  728. /// <returns>Task{IUserRepository}.</returns>
  729. private async Task<IFileOrganizationRepository> GetFileOrganizationRepository()
  730. {
  731. var repo = new SqliteFileOrganizationRepository(LogManager, ServerConfigurationManager.ApplicationPaths, NativeApp.GetDbConnector());
  732. await repo.Initialize().ConfigureAwait(false);
  733. return repo;
  734. }
  735. private async Task<IAuthenticationRepository> GetAuthenticationRepository()
  736. {
  737. var repo = new AuthenticationRepository(LogManager, ServerConfigurationManager.ApplicationPaths, NativeApp.GetDbConnector());
  738. await repo.Initialize().ConfigureAwait(false);
  739. return repo;
  740. }
  741. private async Task<IActivityRepository> GetActivityLogRepository()
  742. {
  743. var repo = new ActivityRepository(LogManager, ServerConfigurationManager.ApplicationPaths, NativeApp.GetDbConnector());
  744. await repo.Initialize().ConfigureAwait(false);
  745. return repo;
  746. }
  747. private async Task<ISyncRepository> GetSyncRepository()
  748. {
  749. var repo = new SyncRepository(LogManager, JsonSerializer, ServerConfigurationManager.ApplicationPaths, NativeApp.GetDbConnector());
  750. await repo.Initialize().ConfigureAwait(false);
  751. return repo;
  752. }
  753. /// <summary>
  754. /// Configures the repositories.
  755. /// </summary>
  756. private async Task ConfigureNotificationsRepository()
  757. {
  758. var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths, NativeApp.GetDbConnector());
  759. await repo.Initialize().ConfigureAwait(false);
  760. NotificationsRepository = repo;
  761. RegisterSingleInstance(NotificationsRepository);
  762. }
  763. /// <summary>
  764. /// Dirty hacks
  765. /// </summary>
  766. private void SetStaticProperties()
  767. {
  768. // For now there's no real way to inject these properly
  769. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  770. BaseItem.ConfigurationManager = ServerConfigurationManager;
  771. BaseItem.LibraryManager = LibraryManager;
  772. BaseItem.ProviderManager = ProviderManager;
  773. BaseItem.LocalizationManager = LocalizationManager;
  774. BaseItem.ItemRepository = ItemRepository;
  775. User.XmlSerializer = XmlSerializer;
  776. User.UserManager = UserManager;
  777. Folder.UserManager = UserManager;
  778. BaseItem.FileSystem = FileSystemManager;
  779. BaseItem.UserDataManager = UserDataManager;
  780. BaseItem.ChannelManager = ChannelManager;
  781. BaseItem.LiveTvManager = LiveTvManager;
  782. Folder.UserViewManager = UserViewManager;
  783. UserView.TVSeriesManager = TVSeriesManager;
  784. UserView.PlaylistManager = PlaylistManager;
  785. BaseItem.CollectionManager = CollectionManager;
  786. BaseItem.MediaSourceManager = MediaSourceManager;
  787. CollectionFolder.XmlSerializer = XmlSerializer;
  788. BaseStreamingService.AppHost = this;
  789. BaseStreamingService.HttpClient = HttpClient;
  790. Utilities.CryptographyProvider = CryptographyProvider;
  791. AuthenticatedAttribute.AuthService = AuthService;
  792. }
  793. /// <summary>
  794. /// Finds the parts.
  795. /// </summary>
  796. protected override void FindParts()
  797. {
  798. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  799. {
  800. RegisterServerWithAdministratorAccess();
  801. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  802. ConfigurationManager.SaveConfiguration();
  803. }
  804. RegisterModules();
  805. base.FindParts();
  806. HttpServer.Init(GetExports<IService>(false));
  807. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  808. StartServer();
  809. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  810. GetExports<IVirtualFolderCreator>(),
  811. GetExports<IItemResolver>(),
  812. GetExports<IIntroProvider>(),
  813. GetExports<IBaseItemComparer>(),
  814. GetExports<ILibraryPostScanTask>());
  815. ProviderManager.AddParts(GetExports<IImageProvider>(),
  816. GetExports<IMetadataService>(),
  817. GetExports<IMetadataProvider>(),
  818. GetExports<IMetadataSaver>(),
  819. GetExports<IExternalId>());
  820. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  821. LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  822. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  823. SessionManager.AddParts(GetExports<ISessionControllerFactory>());
  824. ChannelManager.AddParts(GetExports<IChannel>());
  825. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  826. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  827. SyncManager.AddParts(GetExports<ISyncProvider>());
  828. }
  829. private string CertificatePath { get; set; }
  830. private ICertificate Certificate { get; set; }
  831. private IEnumerable<string> GetUrlPrefixes()
  832. {
  833. var hosts = new List<string>();
  834. hosts.Add("+");
  835. return hosts.SelectMany(i =>
  836. {
  837. var prefixes = new List<string>
  838. {
  839. "http://"+i+":" + HttpPort + "/"
  840. };
  841. if (!string.IsNullOrWhiteSpace(CertificatePath))
  842. {
  843. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  844. }
  845. return prefixes;
  846. });
  847. }
  848. /// <summary>
  849. /// Starts the server.
  850. /// </summary>
  851. private void StartServer()
  852. {
  853. CertificatePath = GetCertificatePath(true);
  854. Certificate = GetCertificate(CertificatePath);
  855. try
  856. {
  857. ServerManager.Start(GetUrlPrefixes());
  858. return;
  859. }
  860. catch (Exception ex)
  861. {
  862. Logger.ErrorException("Error starting http server", ex);
  863. if (HttpPort == ServerConfiguration.DefaultHttpPort)
  864. {
  865. throw;
  866. }
  867. }
  868. HttpPort = ServerConfiguration.DefaultHttpPort;
  869. try
  870. {
  871. ServerManager.Start(GetUrlPrefixes());
  872. }
  873. catch (Exception ex)
  874. {
  875. Logger.ErrorException("Error starting http server", ex);
  876. throw;
  877. }
  878. }
  879. private string GetCertificatePath(bool generateCertificate)
  880. {
  881. if (!string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.CertificatePath))
  882. {
  883. // Custom cert
  884. return ServerConfigurationManager.Configuration.CertificatePath;
  885. }
  886. // Generate self-signed cert
  887. var certHost = GetHostnameFromExternalDns(ServerConfigurationManager.Configuration.WanDdns);
  888. var certPath = Path.Combine(ServerConfigurationManager.ApplicationPaths.ProgramDataPath, "ssl", "cert_" + (certHost + "1").GetMD5().ToString("N") + ".pfx");
  889. if (generateCertificate)
  890. {
  891. if (!FileSystemManager.FileExists(certPath))
  892. {
  893. FileSystemManager.CreateDirectory(Path.GetDirectoryName(certPath));
  894. try
  895. {
  896. NetworkManager.GenerateSelfSignedSslCertificate(certPath, certHost);
  897. }
  898. catch (Exception ex)
  899. {
  900. Logger.ErrorException("Error creating ssl cert", ex);
  901. return null;
  902. }
  903. }
  904. }
  905. return certPath;
  906. }
  907. /// <summary>
  908. /// Called when [configuration updated].
  909. /// </summary>
  910. /// <param name="sender">The sender.</param>
  911. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  912. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  913. {
  914. base.OnConfigurationUpdated(sender, e);
  915. var requiresRestart = false;
  916. // Don't do anything if these haven't been set yet
  917. if (HttpPort != 0 && HttpsPort != 0)
  918. {
  919. // Need to restart if ports have changed
  920. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  921. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  922. {
  923. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  924. {
  925. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  926. ServerConfigurationManager.SaveConfiguration();
  927. requiresRestart = true;
  928. }
  929. }
  930. }
  931. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  932. {
  933. requiresRestart = true;
  934. }
  935. if (!string.Equals(CertificatePath, GetCertificatePath(false), StringComparison.OrdinalIgnoreCase))
  936. {
  937. requiresRestart = true;
  938. }
  939. if (requiresRestart)
  940. {
  941. NotifyPendingRestart();
  942. }
  943. }
  944. /// <summary>
  945. /// Restarts this instance.
  946. /// </summary>
  947. public override async Task Restart()
  948. {
  949. if (!CanSelfRestart)
  950. {
  951. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  952. }
  953. try
  954. {
  955. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  956. }
  957. catch (Exception ex)
  958. {
  959. Logger.ErrorException("Error sending server restart notification", ex);
  960. }
  961. Logger.Info("Calling NativeApp.Restart");
  962. NativeApp.Restart(_startupOptions);
  963. }
  964. /// <summary>
  965. /// Gets or sets a value indicating whether this instance can self update.
  966. /// </summary>
  967. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  968. public override bool CanSelfUpdate
  969. {
  970. get
  971. {
  972. #if DEBUG
  973. return false;
  974. #endif
  975. #pragma warning disable 162
  976. return NativeApp.CanSelfUpdate;
  977. #pragma warning restore 162
  978. }
  979. }
  980. /// <summary>
  981. /// Gets the composable part assemblies.
  982. /// </summary>
  983. /// <returns>IEnumerable{Assembly}.</returns>
  984. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  985. {
  986. var list = GetPluginAssemblies()
  987. .ToList();
  988. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  989. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  990. // Include composable parts in the Api assembly
  991. list.Add(typeof(ApiEntryPoint).Assembly);
  992. // Include composable parts in the Dashboard assembly
  993. list.Add(typeof(DashboardService).Assembly);
  994. // Include composable parts in the Model assembly
  995. list.Add(typeof(SystemInfo).Assembly);
  996. // Include composable parts in the Common assembly
  997. list.Add(typeof(IApplicationHost).Assembly);
  998. // Include composable parts in the Controller assembly
  999. list.Add(typeof(IServerApplicationHost).Assembly);
  1000. // Include composable parts in the Providers assembly
  1001. list.Add(typeof(ProviderUtils).Assembly);
  1002. // Include composable parts in the Photos assembly
  1003. list.Add(typeof(PhotoProvider).Assembly);
  1004. // Common implementations
  1005. list.Add(typeof(TaskManager).Assembly);
  1006. // MediaBrowser.Server implementations
  1007. list.Add(typeof(ServerApplicationPaths).Assembly);
  1008. // Emby.Server implementations
  1009. list.Add(typeof(InstallationManager).Assembly);
  1010. // MediaEncoding
  1011. list.Add(typeof(MediaEncoder).Assembly);
  1012. // Dlna
  1013. list.Add(typeof(DlnaEntryPoint).Assembly);
  1014. // Local metadata
  1015. list.Add(typeof(BoxSetXmlSaver).Assembly);
  1016. // Xbmc
  1017. list.Add(typeof(ArtistNfoProvider).Assembly);
  1018. list.AddRange(NativeApp.GetAssembliesWithParts());
  1019. // Include composable parts in the running assembly
  1020. list.Add(GetType().Assembly);
  1021. return list;
  1022. }
  1023. /// <summary>
  1024. /// Gets the plugin assemblies.
  1025. /// </summary>
  1026. /// <returns>IEnumerable{Assembly}.</returns>
  1027. private IEnumerable<Assembly> GetPluginAssemblies()
  1028. {
  1029. try
  1030. {
  1031. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  1032. .Where(EnablePlugin)
  1033. .Select(LoadAssembly)
  1034. .Where(a => a != null)
  1035. .ToList();
  1036. }
  1037. catch (DirectoryNotFoundException)
  1038. {
  1039. return new List<Assembly>();
  1040. }
  1041. }
  1042. private bool EnablePlugin(string path)
  1043. {
  1044. var filename = Path.GetFileName(path);
  1045. var exclude = new[]
  1046. {
  1047. "mbplus.dll",
  1048. "mbintros.dll"
  1049. };
  1050. return !exclude.Contains(filename ?? string.Empty, StringComparer.OrdinalIgnoreCase);
  1051. }
  1052. /// <summary>
  1053. /// Gets the system status.
  1054. /// </summary>
  1055. /// <returns>SystemInfo.</returns>
  1056. public async Task<SystemInfo> GetSystemInfo()
  1057. {
  1058. var localAddress = await GetLocalApiUrl().ConfigureAwait(false);
  1059. return new SystemInfo
  1060. {
  1061. HasPendingRestart = HasPendingRestart,
  1062. Version = ApplicationVersion.ToString(),
  1063. IsNetworkDeployed = CanSelfUpdate,
  1064. WebSocketPortNumber = HttpPort,
  1065. FailedPluginAssemblies = FailedAssemblies.ToList(),
  1066. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  1067. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  1068. Id = SystemId,
  1069. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1070. LogPath = ApplicationPaths.LogDirectoryPath,
  1071. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  1072. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1073. CachePath = ApplicationPaths.CachePath,
  1074. MacAddress = GetMacAddress(),
  1075. HttpServerPortNumber = HttpPort,
  1076. SupportsHttps = SupportsHttps,
  1077. HttpsPortNumber = HttpsPort,
  1078. OperatingSystem = NativeApp.Environment.OperatingSystem.ToString(),
  1079. OperatingSystemDisplayName = OperatingSystemDisplayName,
  1080. CanSelfRestart = CanSelfRestart,
  1081. CanSelfUpdate = CanSelfUpdate,
  1082. WanAddress = ConnectManager.WanApiAddress,
  1083. HasUpdateAvailable = HasUpdateAvailable,
  1084. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  1085. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  1086. IsRunningAsService = IsRunningAsService,
  1087. SupportsRunningAsService = SupportsRunningAsService,
  1088. ServerName = FriendlyName,
  1089. LocalAddress = localAddress,
  1090. SupportsLibraryMonitor = SupportsLibraryMonitor,
  1091. EncoderLocationType = MediaEncoder.EncoderLocationType,
  1092. SystemArchitecture = NativeApp.Environment.SystemArchitecture,
  1093. SystemUpdateLevel = ConfigurationManager.CommonConfiguration.SystemUpdateLevel,
  1094. PackageName = _startupOptions.GetOption("-package")
  1095. };
  1096. }
  1097. public bool EnableHttps
  1098. {
  1099. get
  1100. {
  1101. return SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1102. }
  1103. }
  1104. public bool SupportsHttps
  1105. {
  1106. get { return Certificate != null; }
  1107. }
  1108. public async Task<string> GetLocalApiUrl()
  1109. {
  1110. try
  1111. {
  1112. // Return the first matched address, if found, or the first known local address
  1113. var address = (await GetLocalIpAddresses().ConfigureAwait(false)).FirstOrDefault(i => !i.Equals(IpAddressInfo.Loopback) && !i.Equals(IpAddressInfo.IPv6Loopback));
  1114. if (address != null)
  1115. {
  1116. return GetLocalApiUrl(address);
  1117. }
  1118. return null;
  1119. }
  1120. catch (Exception ex)
  1121. {
  1122. Logger.ErrorException("Error getting local Ip address information", ex);
  1123. }
  1124. return null;
  1125. }
  1126. public string GetLocalApiUrl(IpAddressInfo ipAddress)
  1127. {
  1128. if (ipAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
  1129. {
  1130. return GetLocalApiUrl("[" + ipAddress.Address + "]");
  1131. }
  1132. return GetLocalApiUrl(ipAddress.Address);
  1133. }
  1134. public string GetLocalApiUrl(string host)
  1135. {
  1136. return string.Format("http://{0}:{1}",
  1137. host,
  1138. HttpPort.ToString(CultureInfo.InvariantCulture));
  1139. }
  1140. public async Task<List<IpAddressInfo>> GetLocalIpAddresses()
  1141. {
  1142. var addresses = NetworkManager.GetLocalIpAddresses().ToList();
  1143. var list = new List<IpAddressInfo>();
  1144. foreach (var address in addresses)
  1145. {
  1146. var valid = await IsIpAddressValidAsync(address).ConfigureAwait(false);
  1147. if (valid)
  1148. {
  1149. list.Add(address);
  1150. }
  1151. }
  1152. return list;
  1153. }
  1154. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1155. private DateTime _lastAddressCacheClear;
  1156. private async Task<bool> IsIpAddressValidAsync(IpAddressInfo address)
  1157. {
  1158. if (address.Equals(IpAddressInfo.Loopback) ||
  1159. address.Equals(IpAddressInfo.IPv6Loopback))
  1160. {
  1161. return true;
  1162. }
  1163. var apiUrl = GetLocalApiUrl(address);
  1164. apiUrl += "/system/ping";
  1165. if ((DateTime.UtcNow - _lastAddressCacheClear).TotalMinutes >= 15)
  1166. {
  1167. _lastAddressCacheClear = DateTime.UtcNow;
  1168. _validAddressResults.Clear();
  1169. }
  1170. bool cachedResult;
  1171. if (_validAddressResults.TryGetValue(apiUrl, out cachedResult))
  1172. {
  1173. return cachedResult;
  1174. }
  1175. try
  1176. {
  1177. using (var response = await HttpClient.SendAsync(new HttpRequestOptions
  1178. {
  1179. Url = apiUrl,
  1180. LogErrorResponseBody = false,
  1181. LogErrors = false,
  1182. LogRequest = false,
  1183. TimeoutMs = 30000,
  1184. BufferContent = false
  1185. }, "POST").ConfigureAwait(false))
  1186. {
  1187. using (var reader = new StreamReader(response.Content))
  1188. {
  1189. var result = reader.ReadToEnd();
  1190. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1191. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1192. //Logger.Debug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1193. return valid;
  1194. }
  1195. }
  1196. }
  1197. catch
  1198. {
  1199. //Logger.Debug("Ping test result to {0}. Success: {1}", apiUrl, false);
  1200. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1201. return false;
  1202. }
  1203. }
  1204. public string FriendlyName
  1205. {
  1206. get
  1207. {
  1208. return string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.ServerName)
  1209. ? Environment.MachineName
  1210. : ServerConfigurationManager.Configuration.ServerName;
  1211. }
  1212. }
  1213. public int HttpPort { get; private set; }
  1214. public int HttpsPort { get; private set; }
  1215. /// <summary>
  1216. /// Gets the mac address.
  1217. /// </summary>
  1218. /// <returns>System.String.</returns>
  1219. private string GetMacAddress()
  1220. {
  1221. try
  1222. {
  1223. return NetworkManager.GetMacAddress();
  1224. }
  1225. catch (Exception ex)
  1226. {
  1227. Logger.ErrorException("Error getting mac address", ex);
  1228. return null;
  1229. }
  1230. }
  1231. /// <summary>
  1232. /// Shuts down.
  1233. /// </summary>
  1234. public override async Task Shutdown()
  1235. {
  1236. try
  1237. {
  1238. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1239. }
  1240. catch (Exception ex)
  1241. {
  1242. Logger.ErrorException("Error sending server shutdown notification", ex);
  1243. }
  1244. NativeApp.Shutdown();
  1245. }
  1246. /// <summary>
  1247. /// Registers the server with administrator access.
  1248. /// </summary>
  1249. private void RegisterServerWithAdministratorAccess()
  1250. {
  1251. Logger.Info("Requesting administrative access to authorize http server");
  1252. try
  1253. {
  1254. NativeApp.AuthorizeServer(
  1255. UdpServerEntryPoint.PortNumber,
  1256. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  1257. ServerConfigurationManager.Configuration.HttpsPortNumber,
  1258. ConfigurationManager.CommonApplicationPaths.ApplicationPath,
  1259. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  1260. }
  1261. catch (Exception ex)
  1262. {
  1263. Logger.ErrorException("Error authorizing server", ex);
  1264. }
  1265. }
  1266. public event EventHandler HasUpdateAvailableChanged;
  1267. private bool _hasUpdateAvailable;
  1268. public bool HasUpdateAvailable
  1269. {
  1270. get { return _hasUpdateAvailable; }
  1271. set
  1272. {
  1273. var fireEvent = value && !_hasUpdateAvailable;
  1274. _hasUpdateAvailable = value;
  1275. if (fireEvent)
  1276. {
  1277. EventHelper.FireEventIfNotNull(HasUpdateAvailableChanged, this, EventArgs.Empty, Logger);
  1278. }
  1279. }
  1280. }
  1281. /// <summary>
  1282. /// Checks for update.
  1283. /// </summary>
  1284. /// <param name="cancellationToken">The cancellation token.</param>
  1285. /// <param name="progress">The progress.</param>
  1286. /// <returns>Task{CheckForUpdateResult}.</returns>
  1287. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  1288. {
  1289. var cacheLength = TimeSpan.FromHours(3);
  1290. var updateLevel = ConfigurationManager.CommonConfiguration.SystemUpdateLevel;
  1291. if (updateLevel == PackageVersionClass.Beta)
  1292. {
  1293. cacheLength = TimeSpan.FromHours(1);
  1294. }
  1295. else if (updateLevel == PackageVersionClass.Dev)
  1296. {
  1297. cacheLength = TimeSpan.FromMinutes(5);
  1298. }
  1299. var result = await new GithubUpdater(HttpClient, JsonSerializer).CheckForUpdateResult("MediaBrowser", "Emby", ApplicationVersion, updateLevel, _releaseAssetFilename,
  1300. "MBServer", "Mbserver.zip", cacheLength, cancellationToken).ConfigureAwait(false);
  1301. HasUpdateAvailable = result.IsUpdateAvailable;
  1302. return result;
  1303. }
  1304. /// <summary>
  1305. /// Updates the application.
  1306. /// </summary>
  1307. /// <param name="package">The package that contains the update</param>
  1308. /// <param name="cancellationToken">The cancellation token.</param>
  1309. /// <param name="progress">The progress.</param>
  1310. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  1311. {
  1312. await InstallationManager.InstallPackage(package, false, progress, cancellationToken).ConfigureAwait(false);
  1313. HasUpdateAvailable = false;
  1314. OnApplicationUpdated(package);
  1315. }
  1316. /// <summary>
  1317. /// Configures the automatic run at startup.
  1318. /// </summary>
  1319. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  1320. protected override void ConfigureAutoRunAtStartup(bool autorun)
  1321. {
  1322. if (SupportsAutoRunAtStartup)
  1323. {
  1324. NativeApp.ConfigureAutoRun(autorun);
  1325. }
  1326. }
  1327. /// <summary>
  1328. /// This returns localhost in the case of no external dns, and the hostname if the
  1329. /// dns is prefixed with a valid Uri prefix.
  1330. /// </summary>
  1331. /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
  1332. /// <returns>The hostname in <paramref name="externalDns"/></returns>
  1333. private static string GetHostnameFromExternalDns(string externalDns)
  1334. {
  1335. if (string.IsNullOrWhiteSpace(externalDns))
  1336. {
  1337. return "localhost";
  1338. }
  1339. try
  1340. {
  1341. return new Uri(externalDns).Host;
  1342. }
  1343. catch
  1344. {
  1345. return externalDns;
  1346. }
  1347. }
  1348. public void LaunchUrl(string url)
  1349. {
  1350. NativeApp.LaunchUrl(url);
  1351. }
  1352. public void EnableLoopback(string appName)
  1353. {
  1354. NativeApp.EnableLoopback(appName);
  1355. }
  1356. private void RegisterModules()
  1357. {
  1358. var moduleTypes = GetExportTypes<IDependencyModule>();
  1359. foreach (var type in moduleTypes)
  1360. {
  1361. try
  1362. {
  1363. var instance = Activator.CreateInstance(type) as IDependencyModule;
  1364. if (instance != null)
  1365. instance.BindDependencies(this);
  1366. }
  1367. catch (Exception ex)
  1368. {
  1369. Logger.ErrorException("Error setting up dependency bindings for " + type.Name, ex);
  1370. }
  1371. }
  1372. }
  1373. void IDependencyContainer.RegisterSingleInstance<T>(T obj, bool manageLifetime)
  1374. {
  1375. RegisterSingleInstance(obj, manageLifetime);
  1376. }
  1377. void IDependencyContainer.RegisterSingleInstance<T>(Func<T> func)
  1378. {
  1379. RegisterSingleInstance(func);
  1380. }
  1381. void IDependencyContainer.Register(Type typeInterface, Type typeImplementation)
  1382. {
  1383. Container.Register(typeInterface, typeImplementation);
  1384. }
  1385. }
  1386. }