ApplicationHost.cs 74 KB

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