ApplicationHost.cs 74 KB

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