ApplicationHost.cs 72 KB

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