ApplicationHost.cs 72 KB

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