ApplicationHost.cs 73 KB

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