ApplicationHost.cs 82 KB

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