ApplicationHost.cs 75 KB

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