ApplicationHost.cs 76 KB

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