ApplicationHost.cs 77 KB

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