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