ApplicationHost.cs 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  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. };
  445. foreach (var task in migrations)
  446. {
  447. try
  448. {
  449. task.Run();
  450. }
  451. catch (Exception ex)
  452. {
  453. Logger.ErrorException("Error running migration", ex);
  454. }
  455. }
  456. }
  457. /// <summary>
  458. /// Registers resources that classes will depend on
  459. /// </summary>
  460. protected override async Task RegisterResources(IProgress<double> progress)
  461. {
  462. await base.RegisterResources(progress).ConfigureAwait(false);
  463. RegisterSingleInstance(PowerManagement);
  464. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LogManager, FileSystemManager, CryptographyProvider);
  465. RegisterSingleInstance(SecurityManager);
  466. InstallationManager = new InstallationManager(LogManager.GetLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ConfigurationManager, FileSystemManager, CryptographyProvider);
  467. RegisterSingleInstance(InstallationManager);
  468. ZipClient = new ZipClient(FileSystemManager);
  469. RegisterSingleInstance(ZipClient);
  470. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer, MemoryStreamFactory));
  471. RegisterSingleInstance<IServerApplicationHost>(this);
  472. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  473. RegisterSingleInstance(ServerConfigurationManager);
  474. IAssemblyInfo assemblyInfo = new AssemblyInfo();
  475. RegisterSingleInstance<IAssemblyInfo>(assemblyInfo);
  476. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LogManager.GetLogger("LocalizationManager"), assemblyInfo, new TextLocalizer());
  477. StringExtensions.LocalizationManager = LocalizationManager;
  478. RegisterSingleInstance(LocalizationManager);
  479. ITextEncoding textEncoding = new TextEncoding(FileSystemManager);
  480. RegisterSingleInstance(textEncoding);
  481. Utilities.EncodingHelper = textEncoding;
  482. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer(FileSystemManager, textEncoding));
  483. RegisterSingleInstance<IXmlReaderSettingsFactory>(new XmlReaderSettingsFactory());
  484. UserDataManager = new UserDataManager(LogManager, ServerConfigurationManager);
  485. RegisterSingleInstance(UserDataManager);
  486. UserRepository = GetUserRepository();
  487. var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LogManager.GetLogger("SqliteDisplayPreferencesRepository"), JsonSerializer, ApplicationPaths, MemoryStreamFactory);
  488. DisplayPreferencesRepository = displayPreferencesRepo;
  489. RegisterSingleInstance(DisplayPreferencesRepository);
  490. var itemRepo = new SqliteItemRepository(ServerConfigurationManager, JsonSerializer, LogManager.GetLogger("SqliteItemRepository"), MemoryStreamFactory, assemblyInfo, FileSystemManager, EnvironmentInfo, TimerFactory);
  491. ItemRepository = itemRepo;
  492. RegisterSingleInstance(ItemRepository);
  493. FileOrganizationRepository = GetFileOrganizationRepository();
  494. RegisterSingleInstance(FileOrganizationRepository);
  495. AuthenticationRepository = await GetAuthenticationRepository().ConfigureAwait(false);
  496. RegisterSingleInstance(AuthenticationRepository);
  497. SyncRepository = GetSyncRepository();
  498. RegisterSingleInstance(SyncRepository);
  499. UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, () => ConnectManager, this, JsonSerializer, FileSystemManager, CryptographyProvider, _defaultUserNameFactory());
  500. RegisterSingleInstance(UserManager);
  501. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
  502. RegisterSingleInstance(LibraryManager);
  503. var musicManager = new MusicManager(LibraryManager);
  504. RegisterSingleInstance<IMusicManager>(new MusicManager(LibraryManager));
  505. LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager, TimerFactory, SystemEvents, EnvironmentInfo);
  506. RegisterSingleInstance(LibraryMonitor);
  507. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer, MemoryStreamFactory);
  508. RegisterSingleInstance(ProviderManager);
  509. RegisterSingleInstance<ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager));
  510. CertificatePath = GetCertificatePath(true);
  511. Certificate = GetCertificate(CertificatePath);
  512. HttpServer = HttpServerFactory.CreateServer(this, LogManager, ServerConfigurationManager, NetworkManager, MemoryStreamFactory, "Emby", "web/index.html", textEncoding, SocketFactory, CryptographyProvider, JsonSerializer, XmlSerializer, EnvironmentInfo, Certificate, SupportsDualModeSockets);
  513. HttpServer.GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
  514. RegisterSingleInstance(HttpServer, false);
  515. progress.Report(10);
  516. ServerManager = new ServerManager(this, JsonSerializer, LogManager.GetLogger("ServerManager"), ServerConfigurationManager, MemoryStreamFactory, textEncoding);
  517. RegisterSingleInstance(ServerManager);
  518. var innerProgress = new ActionableProgress<double>();
  519. innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15));
  520. ImageProcessor = GetImageProcessor();
  521. RegisterSingleInstance(ImageProcessor);
  522. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  523. RegisterSingleInstance(TVSeriesManager);
  524. SyncManager = new SyncManager(LibraryManager, SyncRepository, ImageProcessor, LogManager.GetLogger("SyncManager"), UserManager, () => DtoService, this, TVSeriesManager, () => MediaEncoder, FileSystemManager, () => SubtitleEncoder, ServerConfigurationManager, UserDataManager, () => MediaSourceManager, JsonSerializer, TaskManager, MemoryStreamFactory);
  525. RegisterSingleInstance(SyncManager);
  526. DtoService = new DtoService(LogManager.GetLogger("DtoService"), LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, SyncManager, this, () => DeviceManager, () => MediaSourceManager, () => LiveTvManager);
  527. RegisterSingleInstance(DtoService);
  528. var encryptionManager = new EncryptionManager();
  529. RegisterSingleInstance<IEncryptionManager>(encryptionManager);
  530. ConnectManager = new ConnectManager(LogManager.GetLogger("ConnectManager"), ApplicationPaths, JsonSerializer, encryptionManager, HttpClient, this, ServerConfigurationManager, UserManager, ProviderManager, SecurityManager, FileSystemManager);
  531. RegisterSingleInstance(ConnectManager);
  532. DeviceManager = new DeviceManager(new DeviceRepository(ApplicationPaths, JsonSerializer, LogManager.GetLogger("DeviceManager"), FileSystemManager), UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LogManager.GetLogger("DeviceManager"), NetworkManager);
  533. RegisterSingleInstance(DeviceManager);
  534. var newsService = new Emby.Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer);
  535. RegisterSingleInstance<INewsService>(newsService);
  536. var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, LogManager.GetLogger("FileOrganizationService"), LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager);
  537. RegisterSingleInstance<IFileOrganizationService>(fileOrganizationService);
  538. progress.Report(15);
  539. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LogManager.GetLogger("ChannelManager"), ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager);
  540. RegisterSingleInstance(ChannelManager);
  541. MediaSourceManager = new MediaSourceManager(ItemRepository, UserManager, LibraryManager, LogManager.GetLogger("MediaSourceManager"), JsonSerializer, FileSystemManager, UserDataManager, TimerFactory);
  542. RegisterSingleInstance(MediaSourceManager);
  543. SessionManager = new SessionManager(UserDataManager, LogManager.GetLogger("SessionManager"), LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager, TimerFactory);
  544. RegisterSingleInstance(SessionManager);
  545. var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer, this, assemblyInfo);
  546. RegisterSingleInstance<IDlnaManager>(dlnaManager);
  547. var connectionManager = new ConnectionManager(dlnaManager, ServerConfigurationManager, LogManager.GetLogger("UpnpConnectionManager"), HttpClient, new XmlReaderSettingsFactory());
  548. RegisterSingleInstance<IConnectionManager>(connectionManager);
  549. CollectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager"), ProviderManager);
  550. RegisterSingleInstance(CollectionManager);
  551. PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager, ProviderManager);
  552. RegisterSingleInstance<IPlaylistManager>(PlaylistManager);
  553. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, ProviderManager, FileSystemManager, SecurityManager);
  554. RegisterSingleInstance(LiveTvManager);
  555. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  556. RegisterSingleInstance(UserViewManager);
  557. var contentDirectory = new ContentDirectory(dlnaManager, UserDataManager, ImageProcessor, LibraryManager, ServerConfigurationManager, UserManager, LogManager.GetLogger("UpnpContentDirectory"), HttpClient, LocalizationManager, ChannelManager, MediaSourceManager, UserViewManager, () => MediaEncoder, new XmlReaderSettingsFactory());
  558. RegisterSingleInstance<IContentDirectory>(contentDirectory);
  559. var mediaRegistrar = new MediaReceiverRegistrar(LogManager.GetLogger("MediaReceiverRegistrar"), HttpClient, ServerConfigurationManager, new XmlReaderSettingsFactory());
  560. RegisterSingleInstance<IMediaReceiverRegistrar>(mediaRegistrar);
  561. NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager);
  562. RegisterSingleInstance(NotificationManager);
  563. SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, MediaSourceManager);
  564. RegisterSingleInstance(SubtitleManager);
  565. RegisterSingleInstance<IDeviceDiscovery>(new DeviceDiscovery(LogManager.GetLogger("IDeviceDiscovery"), ServerConfigurationManager, SocketFactory, TimerFactory));
  566. ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
  567. RegisterSingleInstance(ChapterManager);
  568. await RegisterMediaEncoder(innerProgress).ConfigureAwait(false);
  569. progress.Report(90);
  570. EncodingManager = new EncodingManager(FileSystemManager, Logger, MediaEncoder, ChapterManager, LibraryManager);
  571. RegisterSingleInstance(EncodingManager);
  572. var sharingRepo = new SharingRepository(LogManager.GetLogger("SharingRepository"), ApplicationPaths);
  573. sharingRepo.Initialize();
  574. RegisterSingleInstance<ISharingManager>(new SharingManager(sharingRepo, ServerConfigurationManager, LibraryManager, this));
  575. var activityLogRepo = GetActivityLogRepository();
  576. RegisterSingleInstance(activityLogRepo);
  577. RegisterSingleInstance<IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager));
  578. var authContext = new AuthorizationContext(AuthenticationRepository, ConnectManager);
  579. RegisterSingleInstance<IAuthorizationContext>(authContext);
  580. RegisterSingleInstance<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  581. AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, ConnectManager, SessionManager, DeviceManager);
  582. RegisterSingleInstance<IAuthService>(AuthService);
  583. SubtitleEncoder = new SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, MemoryStreamFactory, ProcessFactory, textEncoding);
  584. RegisterSingleInstance(SubtitleEncoder);
  585. displayPreferencesRepo.Initialize();
  586. var userDataRepo = new SqliteUserDataRepository(LogManager.GetLogger("SqliteUserDataRepository"), ApplicationPaths, FileSystemManager);
  587. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  588. itemRepo.Initialize(userDataRepo);
  589. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  590. ConfigureNotificationsRepository();
  591. progress.Report(100);
  592. SetStaticProperties();
  593. await ((UserManager)UserManager).Initialize().ConfigureAwait(false);
  594. }
  595. protected abstract bool SupportsDualModeSockets { get; }
  596. private ICertificate GetCertificate(string certificateLocation)
  597. {
  598. if (string.IsNullOrWhiteSpace(certificateLocation))
  599. {
  600. return null;
  601. }
  602. try
  603. {
  604. if (!FileSystemManager.FileExists(certificateLocation))
  605. {
  606. return null;
  607. }
  608. X509Certificate2 localCert = new X509Certificate2(certificateLocation);
  609. //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  610. if (!localCert.HasPrivateKey)
  611. {
  612. //throw new FileNotFoundException("Secure requested, no private key included", certificateLocation);
  613. return null;
  614. }
  615. return new Certificate(localCert);
  616. }
  617. catch (Exception ex)
  618. {
  619. Logger.ErrorException("Error loading cert from {0}", ex, certificateLocation);
  620. return null;
  621. }
  622. }
  623. private IImageProcessor GetImageProcessor()
  624. {
  625. var maxConcurrentImageProcesses = Math.Max(Environment.ProcessorCount, 4);
  626. if (StartupOptions.ContainsOption("-imagethreads"))
  627. {
  628. int.TryParse(StartupOptions.GetOption("-imagethreads"), NumberStyles.Any, CultureInfo.InvariantCulture, out maxConcurrentImageProcesses);
  629. }
  630. return new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, ImageEncoder, maxConcurrentImageProcesses, () => LibraryManager, TimerFactory);
  631. }
  632. protected abstract FFMpegInstallInfo GetFfmpegInstallInfo();
  633. /// <summary>
  634. /// Registers the media encoder.
  635. /// </summary>
  636. /// <returns>Task.</returns>
  637. private async Task RegisterMediaEncoder(IProgress<double> progress)
  638. {
  639. string encoderPath = null;
  640. string probePath = null;
  641. var info = await new FFMpegLoader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager, GetFfmpegInstallInfo())
  642. .GetFFMpegInfo(StartupOptions, progress).ConfigureAwait(false);
  643. encoderPath = info.EncoderPath;
  644. probePath = info.ProbePath;
  645. var hasExternalEncoder = string.Equals(info.Version, "external", StringComparison.OrdinalIgnoreCase);
  646. var mediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"),
  647. JsonSerializer,
  648. encoderPath,
  649. probePath,
  650. hasExternalEncoder,
  651. ServerConfigurationManager,
  652. FileSystemManager,
  653. LiveTvManager,
  654. IsoManager,
  655. LibraryManager,
  656. ChannelManager,
  657. SessionManager,
  658. () => SubtitleEncoder,
  659. () => MediaSourceManager,
  660. HttpClient,
  661. ZipClient,
  662. MemoryStreamFactory,
  663. ProcessFactory,
  664. (Environment.ProcessorCount > 2 ? 14000 : 40000),
  665. EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows,
  666. EnvironmentInfo);
  667. MediaEncoder = mediaEncoder;
  668. RegisterSingleInstance(MediaEncoder);
  669. }
  670. /// <summary>
  671. /// Gets the user repository.
  672. /// </summary>
  673. /// <returns>Task{IUserRepository}.</returns>
  674. private IUserRepository GetUserRepository()
  675. {
  676. var repo = new SqliteUserRepository(LogManager.GetLogger("SqliteUserRepository"), ApplicationPaths, JsonSerializer, MemoryStreamFactory);
  677. repo.Initialize();
  678. return repo;
  679. }
  680. /// <summary>
  681. /// Gets the file organization repository.
  682. /// </summary>
  683. /// <returns>Task{IUserRepository}.</returns>
  684. private IFileOrganizationRepository GetFileOrganizationRepository()
  685. {
  686. var repo = new SqliteFileOrganizationRepository(LogManager.GetLogger("SqliteFileOrganizationRepository"), ServerConfigurationManager.ApplicationPaths);
  687. repo.Initialize();
  688. return repo;
  689. }
  690. private async Task<IAuthenticationRepository> GetAuthenticationRepository()
  691. {
  692. var repo = new AuthenticationRepository(LogManager.GetLogger("AuthenticationRepository"), ServerConfigurationManager.ApplicationPaths);
  693. repo.Initialize();
  694. return repo;
  695. }
  696. private IActivityRepository GetActivityLogRepository()
  697. {
  698. var repo = new ActivityRepository(LogManager.GetLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths);
  699. repo.Initialize();
  700. return repo;
  701. }
  702. private ISyncRepository GetSyncRepository()
  703. {
  704. var repo = new SyncRepository(LogManager.GetLogger("SyncRepository"), JsonSerializer, ServerConfigurationManager.ApplicationPaths);
  705. repo.Initialize();
  706. return repo;
  707. }
  708. /// <summary>
  709. /// Configures the repositories.
  710. /// </summary>
  711. private void ConfigureNotificationsRepository()
  712. {
  713. var repo = new SqliteNotificationsRepository(LogManager.GetLogger("SqliteNotificationsRepository"), ServerConfigurationManager.ApplicationPaths);
  714. repo.Initialize();
  715. NotificationsRepository = repo;
  716. RegisterSingleInstance(NotificationsRepository);
  717. }
  718. /// <summary>
  719. /// Dirty hacks
  720. /// </summary>
  721. private void SetStaticProperties()
  722. {
  723. // For now there's no real way to inject these properly
  724. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  725. BaseItem.ConfigurationManager = ServerConfigurationManager;
  726. BaseItem.LibraryManager = LibraryManager;
  727. BaseItem.ProviderManager = ProviderManager;
  728. BaseItem.LocalizationManager = LocalizationManager;
  729. BaseItem.ItemRepository = ItemRepository;
  730. User.XmlSerializer = XmlSerializer;
  731. User.UserManager = UserManager;
  732. Folder.UserManager = UserManager;
  733. BaseItem.FileSystem = FileSystemManager;
  734. BaseItem.UserDataManager = UserDataManager;
  735. BaseItem.ChannelManager = ChannelManager;
  736. BaseItem.LiveTvManager = LiveTvManager;
  737. Folder.UserViewManager = UserViewManager;
  738. UserView.TVSeriesManager = TVSeriesManager;
  739. UserView.PlaylistManager = PlaylistManager;
  740. BaseItem.CollectionManager = CollectionManager;
  741. BaseItem.MediaSourceManager = MediaSourceManager;
  742. CollectionFolder.XmlSerializer = XmlSerializer;
  743. BaseStreamingService.AppHost = this;
  744. BaseStreamingService.HttpClient = HttpClient;
  745. Utilities.CryptographyProvider = CryptographyProvider;
  746. AuthenticatedAttribute.AuthService = AuthService;
  747. }
  748. /// <summary>
  749. /// Finds the parts.
  750. /// </summary>
  751. protected override void FindParts()
  752. {
  753. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  754. {
  755. RegisterServerWithAdministratorAccess();
  756. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  757. ConfigurationManager.SaveConfiguration();
  758. }
  759. RegisterModules();
  760. base.FindParts();
  761. HttpServer.Init(GetExports<IService>(false));
  762. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  763. StartServer();
  764. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  765. GetExports<IVirtualFolderCreator>(),
  766. GetExports<IItemResolver>(),
  767. GetExports<IIntroProvider>(),
  768. GetExports<IBaseItemComparer>(),
  769. GetExports<ILibraryPostScanTask>());
  770. ProviderManager.AddParts(GetExports<IImageProvider>(),
  771. GetExports<IMetadataService>(),
  772. GetExports<IMetadataProvider>(),
  773. GetExports<IMetadataSaver>(),
  774. GetExports<IExternalId>());
  775. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  776. LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  777. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  778. SessionManager.AddParts(GetExports<ISessionControllerFactory>());
  779. ChannelManager.AddParts(GetExports<IChannel>());
  780. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  781. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  782. SyncManager.AddParts(GetExports<ISyncProvider>());
  783. }
  784. private string CertificatePath { get; set; }
  785. private ICertificate Certificate { get; set; }
  786. private IEnumerable<string> GetUrlPrefixes()
  787. {
  788. var hosts = new List<string>();
  789. hosts.Add("+");
  790. return hosts.SelectMany(i =>
  791. {
  792. var prefixes = new List<string>
  793. {
  794. "http://"+i+":" + HttpPort + "/"
  795. };
  796. if (!string.IsNullOrWhiteSpace(CertificatePath))
  797. {
  798. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  799. }
  800. return prefixes;
  801. });
  802. }
  803. /// <summary>
  804. /// Starts the server.
  805. /// </summary>
  806. private void StartServer()
  807. {
  808. try
  809. {
  810. ServerManager.Start(GetUrlPrefixes());
  811. return;
  812. }
  813. catch (Exception ex)
  814. {
  815. Logger.ErrorException("Error starting http server", ex);
  816. if (HttpPort == ServerConfiguration.DefaultHttpPort)
  817. {
  818. throw;
  819. }
  820. }
  821. HttpPort = ServerConfiguration.DefaultHttpPort;
  822. try
  823. {
  824. ServerManager.Start(GetUrlPrefixes());
  825. }
  826. catch (Exception ex)
  827. {
  828. Logger.ErrorException("Error starting http server", ex);
  829. throw;
  830. }
  831. }
  832. private string GetCertificatePath(bool generateCertificate)
  833. {
  834. if (!string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.CertificatePath))
  835. {
  836. // Custom cert
  837. return ServerConfigurationManager.Configuration.CertificatePath;
  838. }
  839. // Generate self-signed cert
  840. var certHost = GetHostnameFromExternalDns(ServerConfigurationManager.Configuration.WanDdns);
  841. var certPath = Path.Combine(ServerConfigurationManager.ApplicationPaths.ProgramDataPath, "ssl", "cert_" + (certHost + "1").GetMD5().ToString("N") + ".pfx");
  842. if (generateCertificate)
  843. {
  844. if (!FileSystemManager.FileExists(certPath))
  845. {
  846. FileSystemManager.CreateDirectory(Path.GetDirectoryName(certPath));
  847. try
  848. {
  849. _certificateGenerator(certPath, certHost);
  850. }
  851. catch (Exception ex)
  852. {
  853. Logger.ErrorException("Error creating ssl cert", ex);
  854. return null;
  855. }
  856. }
  857. }
  858. return certPath;
  859. }
  860. /// <summary>
  861. /// Called when [configuration updated].
  862. /// </summary>
  863. /// <param name="sender">The sender.</param>
  864. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  865. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  866. {
  867. base.OnConfigurationUpdated(sender, e);
  868. var requiresRestart = false;
  869. // Don't do anything if these haven't been set yet
  870. if (HttpPort != 0 && HttpsPort != 0)
  871. {
  872. // Need to restart if ports have changed
  873. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  874. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  875. {
  876. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  877. {
  878. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  879. ServerConfigurationManager.SaveConfiguration();
  880. requiresRestart = true;
  881. }
  882. }
  883. }
  884. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  885. {
  886. requiresRestart = true;
  887. }
  888. if (!string.Equals(CertificatePath, GetCertificatePath(false), StringComparison.OrdinalIgnoreCase))
  889. {
  890. requiresRestart = true;
  891. }
  892. if (requiresRestart)
  893. {
  894. NotifyPendingRestart();
  895. }
  896. }
  897. /// <summary>
  898. /// Restarts this instance.
  899. /// </summary>
  900. public override async Task Restart()
  901. {
  902. if (!CanSelfRestart)
  903. {
  904. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  905. }
  906. try
  907. {
  908. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  909. }
  910. catch (Exception ex)
  911. {
  912. Logger.ErrorException("Error sending server restart notification", ex);
  913. }
  914. Logger.Info("Calling RestartInternal");
  915. RestartInternal();
  916. }
  917. protected abstract void RestartInternal();
  918. /// <summary>
  919. /// Gets the composable part assemblies.
  920. /// </summary>
  921. /// <returns>IEnumerable{Assembly}.</returns>
  922. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  923. {
  924. var list = GetPluginAssemblies()
  925. .ToList();
  926. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  927. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  928. // Include composable parts in the Api assembly
  929. list.Add(GetAssembly(typeof(ApiEntryPoint)));
  930. // Include composable parts in the Dashboard assembly
  931. list.Add(GetAssembly(typeof(DashboardService)));
  932. // Include composable parts in the Model assembly
  933. list.Add(GetAssembly(typeof(SystemInfo)));
  934. // Include composable parts in the Common assembly
  935. list.Add(GetAssembly(typeof(IApplicationHost)));
  936. // Include composable parts in the Controller assembly
  937. list.Add(GetAssembly(typeof(IServerApplicationHost)));
  938. // Include composable parts in the Providers assembly
  939. list.Add(GetAssembly(typeof(ProviderUtils)));
  940. // Include composable parts in the Photos assembly
  941. list.Add(GetAssembly(typeof(PhotoProvider)));
  942. // Common implementations
  943. list.Add(GetAssembly(typeof(TaskManager)));
  944. // Emby.Server implementations
  945. list.Add(GetAssembly(typeof(InstallationManager)));
  946. // Emby.Server.Core
  947. list.Add(GetAssembly(typeof(ServerApplicationPaths)));
  948. // MediaEncoding
  949. list.Add(GetAssembly(typeof(MediaEncoder)));
  950. // Dlna
  951. list.Add(GetAssembly(typeof(DlnaEntryPoint)));
  952. // Local metadata
  953. list.Add(GetAssembly(typeof(BoxSetXmlSaver)));
  954. // Xbmc
  955. list.Add(GetAssembly(typeof(ArtistNfoProvider)));
  956. list.AddRange(GetAssembliesWithPartsInternal());
  957. // Include composable parts in the running assembly
  958. list.Add(GetAssembly(typeof(ApplicationHost)));
  959. return list;
  960. }
  961. protected abstract List<Assembly> GetAssembliesWithPartsInternal();
  962. /// <summary>
  963. /// Gets the plugin assemblies.
  964. /// </summary>
  965. /// <returns>IEnumerable{Assembly}.</returns>
  966. private IEnumerable<Assembly> GetPluginAssemblies()
  967. {
  968. try
  969. {
  970. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  971. .Where(EnablePlugin)
  972. .Select(LoadAssembly)
  973. .Where(a => a != null)
  974. .ToList();
  975. }
  976. catch (DirectoryNotFoundException)
  977. {
  978. return new List<Assembly>();
  979. }
  980. }
  981. private bool EnablePlugin(string path)
  982. {
  983. var filename = Path.GetFileName(path);
  984. var exclude = new[]
  985. {
  986. "mbplus.dll",
  987. "mbintros.dll"
  988. };
  989. return !exclude.Contains(filename ?? string.Empty, StringComparer.OrdinalIgnoreCase);
  990. }
  991. /// <summary>
  992. /// Gets the system status.
  993. /// </summary>
  994. /// <returns>SystemInfo.</returns>
  995. public async Task<SystemInfo> GetSystemInfo()
  996. {
  997. var localAddress = await GetLocalApiUrl().ConfigureAwait(false);
  998. return new SystemInfo
  999. {
  1000. HasPendingRestart = HasPendingRestart,
  1001. Version = ApplicationVersion.ToString(),
  1002. WebSocketPortNumber = HttpPort,
  1003. FailedPluginAssemblies = FailedAssemblies.ToList(),
  1004. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  1005. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  1006. Id = SystemId,
  1007. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1008. LogPath = ApplicationPaths.LogDirectoryPath,
  1009. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  1010. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1011. CachePath = ApplicationPaths.CachePath,
  1012. MacAddress = GetMacAddress(),
  1013. HttpServerPortNumber = HttpPort,
  1014. SupportsHttps = SupportsHttps,
  1015. HttpsPortNumber = HttpsPort,
  1016. OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(),
  1017. OperatingSystemDisplayName = OperatingSystemDisplayName,
  1018. CanSelfRestart = CanSelfRestart,
  1019. CanSelfUpdate = CanSelfUpdate,
  1020. WanAddress = ConnectManager.WanApiAddress,
  1021. HasUpdateAvailable = HasUpdateAvailable,
  1022. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  1023. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  1024. IsRunningAsService = IsRunningAsService,
  1025. SupportsRunningAsService = SupportsRunningAsService,
  1026. ServerName = FriendlyName,
  1027. LocalAddress = localAddress,
  1028. SupportsLibraryMonitor = true,
  1029. EncoderLocationType = MediaEncoder.EncoderLocationType,
  1030. SystemArchitecture = EnvironmentInfo.SystemArchitecture,
  1031. SystemUpdateLevel = ConfigurationManager.CommonConfiguration.SystemUpdateLevel,
  1032. PackageName = StartupOptions.GetOption("-package")
  1033. };
  1034. }
  1035. public bool EnableHttps
  1036. {
  1037. get
  1038. {
  1039. return SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1040. }
  1041. }
  1042. public bool SupportsHttps
  1043. {
  1044. get { return Certificate != null; }
  1045. }
  1046. public async Task<string> GetLocalApiUrl()
  1047. {
  1048. try
  1049. {
  1050. // Return the first matched address, if found, or the first known local address
  1051. var address = (await GetLocalIpAddresses().ConfigureAwait(false)).FirstOrDefault(i => !i.Equals(IpAddressInfo.Loopback) && !i.Equals(IpAddressInfo.IPv6Loopback));
  1052. if (address != null)
  1053. {
  1054. return GetLocalApiUrl(address);
  1055. }
  1056. return null;
  1057. }
  1058. catch (Exception ex)
  1059. {
  1060. Logger.ErrorException("Error getting local Ip address information", ex);
  1061. }
  1062. return null;
  1063. }
  1064. public string GetLocalApiUrl(IpAddressInfo ipAddress)
  1065. {
  1066. if (ipAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
  1067. {
  1068. return GetLocalApiUrl("[" + ipAddress.Address + "]");
  1069. }
  1070. return GetLocalApiUrl(ipAddress.Address);
  1071. }
  1072. public string GetLocalApiUrl(string host)
  1073. {
  1074. return string.Format("http://{0}:{1}",
  1075. host,
  1076. HttpPort.ToString(CultureInfo.InvariantCulture));
  1077. }
  1078. public async Task<List<IpAddressInfo>> GetLocalIpAddresses()
  1079. {
  1080. var addresses = ServerConfigurationManager
  1081. .Configuration
  1082. .LocalNetworkAddresses
  1083. .Select(NormalizeConfiguredLocalAddress)
  1084. .Where(i => i != null)
  1085. .ToList();
  1086. if (addresses.Count == 0)
  1087. {
  1088. addresses.AddRange(NetworkManager.GetLocalIpAddresses());
  1089. var list = new List<IpAddressInfo>();
  1090. foreach (var address in addresses)
  1091. {
  1092. var valid = await IsIpAddressValidAsync(address).ConfigureAwait(false);
  1093. if (valid)
  1094. {
  1095. list.Add(address);
  1096. }
  1097. }
  1098. addresses = list;
  1099. }
  1100. return addresses;
  1101. }
  1102. private IpAddressInfo NormalizeConfiguredLocalAddress(string address)
  1103. {
  1104. var index = address.Trim('/').IndexOf('/');
  1105. if (index != -1)
  1106. {
  1107. address = address.Substring(index + 1);
  1108. }
  1109. IpAddressInfo result;
  1110. if (NetworkManager.TryParseIpAddress(address.Trim('/'), out result))
  1111. {
  1112. return result;
  1113. }
  1114. return null;
  1115. }
  1116. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1117. private DateTime _lastAddressCacheClear;
  1118. private async Task<bool> IsIpAddressValidAsync(IpAddressInfo address)
  1119. {
  1120. if (address.Equals(IpAddressInfo.Loopback) ||
  1121. address.Equals(IpAddressInfo.IPv6Loopback))
  1122. {
  1123. return true;
  1124. }
  1125. var apiUrl = GetLocalApiUrl(address);
  1126. apiUrl += "/system/ping";
  1127. if ((DateTime.UtcNow - _lastAddressCacheClear).TotalMinutes >= 15)
  1128. {
  1129. _lastAddressCacheClear = DateTime.UtcNow;
  1130. _validAddressResults.Clear();
  1131. }
  1132. bool cachedResult;
  1133. if (_validAddressResults.TryGetValue(apiUrl, out cachedResult))
  1134. {
  1135. return cachedResult;
  1136. }
  1137. try
  1138. {
  1139. using (var response = await HttpClient.SendAsync(new HttpRequestOptions
  1140. {
  1141. Url = apiUrl,
  1142. LogErrorResponseBody = false,
  1143. LogErrors = false,
  1144. LogRequest = false,
  1145. TimeoutMs = 30000,
  1146. BufferContent = false
  1147. }, "POST").ConfigureAwait(false))
  1148. {
  1149. using (var reader = new StreamReader(response.Content))
  1150. {
  1151. var result = reader.ReadToEnd();
  1152. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1153. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1154. //Logger.Debug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1155. return valid;
  1156. }
  1157. }
  1158. }
  1159. catch
  1160. {
  1161. //Logger.Debug("Ping test result to {0}. Success: {1}", apiUrl, false);
  1162. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1163. return false;
  1164. }
  1165. }
  1166. public string FriendlyName
  1167. {
  1168. get
  1169. {
  1170. return string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.ServerName)
  1171. ? Environment.MachineName
  1172. : ServerConfigurationManager.Configuration.ServerName;
  1173. }
  1174. }
  1175. public int HttpPort { get; private set; }
  1176. public int HttpsPort { get; private set; }
  1177. /// <summary>
  1178. /// Gets the mac address.
  1179. /// </summary>
  1180. /// <returns>System.String.</returns>
  1181. private string GetMacAddress()
  1182. {
  1183. try
  1184. {
  1185. return NetworkManager.GetMacAddress();
  1186. }
  1187. catch (Exception ex)
  1188. {
  1189. Logger.ErrorException("Error getting mac address", ex);
  1190. return null;
  1191. }
  1192. }
  1193. /// <summary>
  1194. /// Shuts down.
  1195. /// </summary>
  1196. public override async Task Shutdown()
  1197. {
  1198. try
  1199. {
  1200. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1201. }
  1202. catch (Exception ex)
  1203. {
  1204. Logger.ErrorException("Error sending server shutdown notification", ex);
  1205. }
  1206. ShutdownInternal();
  1207. }
  1208. protected abstract void ShutdownInternal();
  1209. /// <summary>
  1210. /// Registers the server with administrator access.
  1211. /// </summary>
  1212. private void RegisterServerWithAdministratorAccess()
  1213. {
  1214. Logger.Info("Requesting administrative access to authorize http server");
  1215. try
  1216. {
  1217. AuthorizeServer();
  1218. }
  1219. catch (Exception ex)
  1220. {
  1221. Logger.ErrorException("Error authorizing server", ex);
  1222. }
  1223. }
  1224. protected abstract void AuthorizeServer();
  1225. public event EventHandler HasUpdateAvailableChanged;
  1226. private bool _hasUpdateAvailable;
  1227. public bool HasUpdateAvailable
  1228. {
  1229. get { return _hasUpdateAvailable; }
  1230. set
  1231. {
  1232. var fireEvent = value && !_hasUpdateAvailable;
  1233. _hasUpdateAvailable = value;
  1234. if (fireEvent)
  1235. {
  1236. EventHelper.FireEventIfNotNull(HasUpdateAvailableChanged, this, EventArgs.Empty, Logger);
  1237. }
  1238. }
  1239. }
  1240. /// <summary>
  1241. /// Checks for update.
  1242. /// </summary>
  1243. /// <param name="cancellationToken">The cancellation token.</param>
  1244. /// <param name="progress">The progress.</param>
  1245. /// <returns>Task{CheckForUpdateResult}.</returns>
  1246. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  1247. {
  1248. var cacheLength = TimeSpan.FromHours(3);
  1249. var updateLevel = ConfigurationManager.CommonConfiguration.SystemUpdateLevel;
  1250. if (updateLevel == PackageVersionClass.Beta)
  1251. {
  1252. cacheLength = TimeSpan.FromHours(1);
  1253. }
  1254. else if (updateLevel == PackageVersionClass.Dev)
  1255. {
  1256. cacheLength = TimeSpan.FromMinutes(5);
  1257. }
  1258. var result = await new GithubUpdater(HttpClient, JsonSerializer).CheckForUpdateResult("MediaBrowser", "Emby", ApplicationVersion, updateLevel, _releaseAssetFilename,
  1259. "MBServer", "Mbserver.zip", cacheLength, cancellationToken).ConfigureAwait(false);
  1260. HasUpdateAvailable = result.IsUpdateAvailable;
  1261. return result;
  1262. }
  1263. /// <summary>
  1264. /// Updates the application.
  1265. /// </summary>
  1266. /// <param name="package">The package that contains the update</param>
  1267. /// <param name="cancellationToken">The cancellation token.</param>
  1268. /// <param name="progress">The progress.</param>
  1269. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  1270. {
  1271. await InstallationManager.InstallPackage(package, false, progress, cancellationToken).ConfigureAwait(false);
  1272. HasUpdateAvailable = false;
  1273. OnApplicationUpdated(package);
  1274. }
  1275. /// <summary>
  1276. /// Configures the automatic run at startup.
  1277. /// </summary>
  1278. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  1279. protected override void ConfigureAutoRunAtStartup(bool autorun)
  1280. {
  1281. if (SupportsAutoRunAtStartup)
  1282. {
  1283. ConfigureAutoRunInternal(autorun);
  1284. }
  1285. }
  1286. protected abstract void ConfigureAutoRunInternal(bool autorun);
  1287. /// <summary>
  1288. /// This returns localhost in the case of no external dns, and the hostname if the
  1289. /// dns is prefixed with a valid Uri prefix.
  1290. /// </summary>
  1291. /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
  1292. /// <returns>The hostname in <paramref name="externalDns"/></returns>
  1293. private static string GetHostnameFromExternalDns(string externalDns)
  1294. {
  1295. if (string.IsNullOrWhiteSpace(externalDns))
  1296. {
  1297. return "localhost";
  1298. }
  1299. try
  1300. {
  1301. return new Uri(externalDns).Host;
  1302. }
  1303. catch
  1304. {
  1305. return externalDns;
  1306. }
  1307. }
  1308. public void LaunchUrl(string url)
  1309. {
  1310. if (EnvironmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
  1311. {
  1312. throw new NotImplementedException();
  1313. }
  1314. var process = ProcessFactory.Create(new ProcessOptions
  1315. {
  1316. FileName = url,
  1317. EnableRaisingEvents = true,
  1318. UseShellExecute = true,
  1319. ErrorDialog = false
  1320. });
  1321. process.Exited += ProcessExited;
  1322. try
  1323. {
  1324. process.Start();
  1325. }
  1326. catch (Exception ex)
  1327. {
  1328. Console.WriteLine("Error launching url: {0}", url);
  1329. Logger.ErrorException("Error launching url: {0}", ex, url);
  1330. throw;
  1331. }
  1332. }
  1333. private static void ProcessExited(object sender, EventArgs e)
  1334. {
  1335. ((IProcess)sender).Dispose();
  1336. }
  1337. public void EnableLoopback(string appName)
  1338. {
  1339. EnableLoopbackInternal(appName);
  1340. }
  1341. protected abstract void EnableLoopbackInternal(string appName);
  1342. private void RegisterModules()
  1343. {
  1344. var moduleTypes = GetExportTypes<IDependencyModule>();
  1345. foreach (var type in moduleTypes)
  1346. {
  1347. try
  1348. {
  1349. var instance = Activator.CreateInstance(type) as IDependencyModule;
  1350. if (instance != null)
  1351. instance.BindDependencies(this);
  1352. }
  1353. catch (Exception ex)
  1354. {
  1355. Logger.ErrorException("Error setting up dependency bindings for " + type.Name, ex);
  1356. }
  1357. }
  1358. }
  1359. void IDependencyContainer.RegisterSingleInstance<T>(T obj, bool manageLifetime)
  1360. {
  1361. RegisterSingleInstance(obj, manageLifetime);
  1362. }
  1363. void IDependencyContainer.RegisterSingleInstance<T>(Func<T> func)
  1364. {
  1365. RegisterSingleInstance(func);
  1366. }
  1367. void IDependencyContainer.Register(Type typeInterface, Type typeImplementation)
  1368. {
  1369. Container.Register(typeInterface, typeImplementation);
  1370. }
  1371. }
  1372. }