ApplicationHost.cs 74 KB

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