ApplicationHost.cs 69 KB

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