2
0

ApplicationHost.cs 72 KB

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