ApplicationHost.cs 71 KB

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