ApplicationHost.cs 72 KB

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