ApplicationHost.cs 71 KB

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