ApplicationHost.cs 71 KB

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