ApplicationHost.cs 72 KB

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