ApplicationHost.cs 72 KB

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