ApplicationHost.cs 64 KB

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