ApplicationHost.cs 71 KB

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