ApplicationHost.cs 76 KB

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