ApplicationHost.cs 80 KB

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