ApplicationHost.cs 76 KB

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