ApplicationHost.cs 75 KB

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