ApplicationHost.cs 71 KB

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