ApplicationHost.cs 83 KB

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