ApplicationHost.cs 73 KB

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