ApplicationHost.cs 71 KB

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