ApplicationHost.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. using MediaBrowser.Api;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Configuration;
  4. using MediaBrowser.Common.Events;
  5. using MediaBrowser.Common.Implementations;
  6. using MediaBrowser.Common.Implementations.ScheduledTasks;
  7. using MediaBrowser.Common.IO;
  8. using MediaBrowser.Common.Net;
  9. using MediaBrowser.Common.Progress;
  10. using MediaBrowser.Controller;
  11. using MediaBrowser.Controller.Activity;
  12. using MediaBrowser.Controller.Channels;
  13. using MediaBrowser.Controller.Chapters;
  14. using MediaBrowser.Controller.Collections;
  15. using MediaBrowser.Controller.Configuration;
  16. using MediaBrowser.Controller.Connect;
  17. using MediaBrowser.Controller.Devices;
  18. using MediaBrowser.Controller.Dlna;
  19. using MediaBrowser.Controller.Drawing;
  20. using MediaBrowser.Controller.Dto;
  21. using MediaBrowser.Controller.Entities;
  22. using MediaBrowser.Controller.FileOrganization;
  23. using MediaBrowser.Controller.Library;
  24. using MediaBrowser.Controller.LiveTv;
  25. using MediaBrowser.Controller.Localization;
  26. using MediaBrowser.Controller.MediaEncoding;
  27. using MediaBrowser.Controller.Net;
  28. using MediaBrowser.Controller.News;
  29. using MediaBrowser.Controller.Notifications;
  30. using MediaBrowser.Controller.Persistence;
  31. using MediaBrowser.Controller.Playlists;
  32. using MediaBrowser.Controller.Plugins;
  33. using MediaBrowser.Controller.Providers;
  34. using MediaBrowser.Controller.Resolvers;
  35. using MediaBrowser.Controller.Security;
  36. using MediaBrowser.Controller.Session;
  37. using MediaBrowser.Controller.Sorting;
  38. using MediaBrowser.Controller.Subtitles;
  39. using MediaBrowser.Controller.Sync;
  40. using MediaBrowser.Controller.Themes;
  41. using MediaBrowser.Controller.TV;
  42. using MediaBrowser.Dlna;
  43. using MediaBrowser.Dlna.ConnectionManager;
  44. using MediaBrowser.Dlna.ContentDirectory;
  45. using MediaBrowser.Dlna.Main;
  46. using MediaBrowser.LocalMetadata.Providers;
  47. using MediaBrowser.MediaEncoding.BdInfo;
  48. using MediaBrowser.MediaEncoding.Encoder;
  49. using MediaBrowser.MediaEncoding.Subtitles;
  50. using MediaBrowser.Model.Logging;
  51. using MediaBrowser.Model.MediaInfo;
  52. using MediaBrowser.Model.System;
  53. using MediaBrowser.Model.Updates;
  54. using MediaBrowser.Providers.Chapters;
  55. using MediaBrowser.Providers.Manager;
  56. using MediaBrowser.Providers.Subtitles;
  57. using MediaBrowser.Server.Implementations;
  58. using MediaBrowser.Server.Implementations.Activity;
  59. using MediaBrowser.Server.Implementations.Channels;
  60. using MediaBrowser.Server.Implementations.Collections;
  61. using MediaBrowser.Server.Implementations.Configuration;
  62. using MediaBrowser.Server.Implementations.Connect;
  63. using MediaBrowser.Server.Implementations.Devices;
  64. using MediaBrowser.Server.Implementations.Drawing;
  65. using MediaBrowser.Server.Implementations.Dto;
  66. using MediaBrowser.Server.Implementations.EntryPoints;
  67. using MediaBrowser.Server.Implementations.FileOrganization;
  68. using MediaBrowser.Server.Implementations.HttpServer;
  69. using MediaBrowser.Server.Implementations.HttpServer.Security;
  70. using MediaBrowser.Server.Implementations.IO;
  71. using MediaBrowser.Server.Implementations.Library;
  72. using MediaBrowser.Server.Implementations.LiveTv;
  73. using MediaBrowser.Server.Implementations.Localization;
  74. using MediaBrowser.Server.Implementations.MediaEncoder;
  75. using MediaBrowser.Server.Implementations.Notifications;
  76. using MediaBrowser.Server.Implementations.Persistence;
  77. using MediaBrowser.Server.Implementations.Playlists;
  78. using MediaBrowser.Server.Implementations.Security;
  79. using MediaBrowser.Server.Implementations.ServerManager;
  80. using MediaBrowser.Server.Implementations.Session;
  81. using MediaBrowser.Server.Implementations.Sync;
  82. using MediaBrowser.Server.Implementations.Themes;
  83. using MediaBrowser.Server.Implementations.TV;
  84. using MediaBrowser.Server.Startup.Common.FFMpeg;
  85. using MediaBrowser.Server.Startup.Common.Migrations;
  86. using MediaBrowser.WebDashboard.Api;
  87. using MediaBrowser.XbmcMetadata.Providers;
  88. using System;
  89. using System.Collections.Generic;
  90. using System.Globalization;
  91. using System.IO;
  92. using System.Linq;
  93. using System.Reflection;
  94. using System.Threading;
  95. using System.Threading.Tasks;
  96. namespace MediaBrowser.Server.Startup.Common
  97. {
  98. /// <summary>
  99. /// Class CompositionRoot
  100. /// </summary>
  101. public class ApplicationHost : BaseApplicationHost<ServerApplicationPaths>, IServerApplicationHost
  102. {
  103. /// <summary>
  104. /// Gets the server configuration manager.
  105. /// </summary>
  106. /// <value>The server configuration manager.</value>
  107. public IServerConfigurationManager ServerConfigurationManager
  108. {
  109. get { return (IServerConfigurationManager)ConfigurationManager; }
  110. }
  111. /// <summary>
  112. /// Gets the name of the web application that can be used for url building.
  113. /// All api urls will be of the form {protocol}://{host}:{port}/{appname}/...
  114. /// </summary>
  115. /// <value>The name of the web application.</value>
  116. public string WebApplicationName
  117. {
  118. get { return "mediabrowser"; }
  119. }
  120. /// <summary>
  121. /// Gets the HTTP server URL prefix.
  122. /// </summary>
  123. /// <value>The HTTP server URL prefix.</value>
  124. private IEnumerable<string> HttpServerUrlPrefixes
  125. {
  126. get
  127. {
  128. var list = new List<string>
  129. {
  130. "http://+:" + ServerConfigurationManager.Configuration.HttpServerPortNumber + "/" + WebApplicationName + "/"
  131. };
  132. return list;
  133. }
  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);
  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. private IImageProcessor ImageProcessor { get; set; }
  175. private ISeriesOrderManager SeriesOrderManager { get; set; }
  176. /// <summary>
  177. /// Gets or sets the media encoder.
  178. /// </summary>
  179. /// <value>The media encoder.</value>
  180. private IMediaEncoder MediaEncoder { 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 IFileOrganizationRepository FileOrganizationRepository { get; set; }
  198. private IProviderRepository ProviderRepository { get; set; }
  199. private INotificationManager NotificationManager { get; set; }
  200. private ISubtitleManager SubtitleManager { get; set; }
  201. private IChapterManager ChapterManager { get; set; }
  202. private IDeviceManager DeviceManager { get; set; }
  203. internal IUserViewManager UserViewManager { get; set; }
  204. private IAuthenticationRepository AuthenticationRepository { get; set; }
  205. private ISyncRepository SyncRepository { get; set; }
  206. private ITVSeriesManager TVSeriesManager { get; set; }
  207. private ICollectionManager CollectionManager { get; set; }
  208. private readonly StartupOptions _startupOptions;
  209. private readonly string _remotePackageName;
  210. private readonly bool _supportsNativeWebSocket;
  211. internal INativeApp NativeApp { get; set; }
  212. /// <summary>
  213. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  214. /// </summary>
  215. /// <param name="applicationPaths">The application paths.</param>
  216. /// <param name="logManager">The log manager.</param>
  217. /// <param name="options">The options.</param>
  218. /// <param name="fileSystem">The file system.</param>
  219. /// <param name="remotePackageName">Name of the remote package.</param>
  220. /// <param name="supportsNativeWebSocket">if set to <c>true</c> [supports native web socket].</param>
  221. /// <param name="nativeApp">The native application.</param>
  222. public ApplicationHost(ServerApplicationPaths applicationPaths,
  223. ILogManager logManager,
  224. StartupOptions options,
  225. IFileSystem fileSystem,
  226. string remotePackageName,
  227. bool supportsNativeWebSocket,
  228. INativeApp nativeApp)
  229. : base(applicationPaths, logManager, fileSystem)
  230. {
  231. _startupOptions = options;
  232. _remotePackageName = remotePackageName;
  233. _supportsNativeWebSocket = supportsNativeWebSocket;
  234. NativeApp = nativeApp;
  235. }
  236. public override bool IsRunningAsService
  237. {
  238. get { return NativeApp.IsRunningAsService; }
  239. }
  240. public bool SupportsRunningAsService
  241. {
  242. get { return NativeApp.SupportsRunningAsService; }
  243. }
  244. /// <summary>
  245. /// Gets the name.
  246. /// </summary>
  247. /// <value>The name.</value>
  248. public override string Name
  249. {
  250. get
  251. {
  252. return "Media Browser Server";
  253. }
  254. }
  255. /// <summary>
  256. /// Gets a value indicating whether this instance can self restart.
  257. /// </summary>
  258. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  259. public override bool CanSelfRestart
  260. {
  261. get { return NativeApp.CanSelfRestart; }
  262. }
  263. public bool SupportsAutoRunAtStartup
  264. {
  265. get { return NativeApp.SupportsAutoRunAtStartup; }
  266. }
  267. /// <summary>
  268. /// Runs the startup tasks.
  269. /// </summary>
  270. /// <returns>Task.</returns>
  271. public override async Task RunStartupTasks()
  272. {
  273. await base.RunStartupTasks().ConfigureAwait(false);
  274. Logger.Info("Core startup complete");
  275. Parallel.ForEach(GetExports<IServerEntryPoint>(), entryPoint =>
  276. {
  277. try
  278. {
  279. entryPoint.Run();
  280. }
  281. catch (Exception ex)
  282. {
  283. Logger.ErrorException("Error in {0}", ex, entryPoint.GetType().Name);
  284. }
  285. });
  286. LogManager.RemoveConsoleOutput();
  287. }
  288. public override async Task Init(IProgress<double> progress)
  289. {
  290. PerformVersionMigration();
  291. await base.Init(progress).ConfigureAwait(false);
  292. }
  293. private void PerformVersionMigration()
  294. {
  295. new MigrateUserFolders(ApplicationPaths).Run();
  296. new PlaylistImages(ServerConfigurationManager).Run();
  297. new RenameXbmcOptions(ServerConfigurationManager).Run();
  298. new RenameXmlOptions(ServerConfigurationManager).Run();
  299. }
  300. /// <summary>
  301. /// Registers resources that classes will depend on
  302. /// </summary>
  303. /// <returns>Task.</returns>
  304. protected override async Task RegisterResources(IProgress<double> progress)
  305. {
  306. await base.RegisterResources(progress).ConfigureAwait(false);
  307. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer));
  308. RegisterSingleInstance<IServerApplicationHost>(this);
  309. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  310. RegisterSingleInstance(ServerConfigurationManager);
  311. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer);
  312. RegisterSingleInstance(LocalizationManager);
  313. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  314. UserDataManager = new UserDataManager(LogManager);
  315. RegisterSingleInstance(UserDataManager);
  316. UserRepository = await GetUserRepository().ConfigureAwait(false);
  317. RegisterSingleInstance(UserRepository);
  318. DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
  319. RegisterSingleInstance(DisplayPreferencesRepository);
  320. ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
  321. RegisterSingleInstance(ItemRepository);
  322. ProviderRepository = new SqliteProviderInfoRepository(ApplicationPaths, LogManager);
  323. RegisterSingleInstance(ProviderRepository);
  324. FileOrganizationRepository = await GetFileOrganizationRepository().ConfigureAwait(false);
  325. RegisterSingleInstance(FileOrganizationRepository);
  326. AuthenticationRepository = await GetAuthenticationRepository().ConfigureAwait(false);
  327. RegisterSingleInstance(AuthenticationRepository);
  328. //SyncRepository = await GetSyncRepository().ConfigureAwait(false);
  329. //RegisterSingleInstance(SyncRepository);
  330. UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, () => ConnectManager, this);
  331. RegisterSingleInstance(UserManager);
  332. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager);
  333. RegisterSingleInstance(LibraryManager);
  334. var musicManager = new MusicManager(LibraryManager);
  335. RegisterSingleInstance<IMusicManager>(new MusicManager(LibraryManager));
  336. LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager);
  337. RegisterSingleInstance(LibraryMonitor);
  338. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager);
  339. RegisterSingleInstance(ProviderManager);
  340. SeriesOrderManager = new SeriesOrderManager();
  341. RegisterSingleInstance(SeriesOrderManager);
  342. RegisterSingleInstance<ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager));
  343. HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", WebApplicationName, "dashboard/index.html", _supportsNativeWebSocket);
  344. RegisterSingleInstance(HttpServer, false);
  345. progress.Report(10);
  346. ServerManager = new ServerManager(this, JsonSerializer, LogManager.GetLogger("ServerManager"), ServerConfigurationManager);
  347. RegisterSingleInstance(ServerManager);
  348. var innerProgress = new ActionableProgress<double>();
  349. innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15));
  350. await RegisterMediaEncoder(innerProgress).ConfigureAwait(false);
  351. progress.Report(90);
  352. ImageProcessor = new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, MediaEncoder);
  353. RegisterSingleInstance(ImageProcessor);
  354. SyncManager = new SyncManager(LibraryManager, SyncRepository, ImageProcessor, LogManager.GetLogger("SyncManager"));
  355. RegisterSingleInstance(SyncManager);
  356. DtoService = new DtoService(Logger, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, SyncManager, this);
  357. RegisterSingleInstance(DtoService);
  358. var encryptionManager = new EncryptionManager();
  359. RegisterSingleInstance<IEncryptionManager>(encryptionManager);
  360. ConnectManager = new ConnectManager(LogManager.GetLogger("Connect"), ApplicationPaths, JsonSerializer, encryptionManager, HttpClient, this, ServerConfigurationManager, UserManager, ProviderManager);
  361. RegisterSingleInstance(ConnectManager);
  362. DeviceManager = new DeviceManager(new DeviceRepository(ApplicationPaths, JsonSerializer, Logger), UserManager, FileSystemManager, LibraryMonitor, ConfigurationManager, LogManager.GetLogger("DeviceManager"));
  363. RegisterSingleInstance(DeviceManager);
  364. SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, ItemRepository, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager);
  365. RegisterSingleInstance(SessionManager);
  366. var newsService = new Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer);
  367. RegisterSingleInstance<INewsService>(newsService);
  368. var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, LogManager.GetLogger("FileOrganizationService"), LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager);
  369. RegisterSingleInstance<IFileOrganizationService>(fileOrganizationService);
  370. progress.Report(15);
  371. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, Logger, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient);
  372. RegisterSingleInstance(ChannelManager);
  373. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager);
  374. RegisterSingleInstance(TVSeriesManager);
  375. var appThemeManager = new AppThemeManager(ApplicationPaths, FileSystemManager, JsonSerializer, Logger);
  376. RegisterSingleInstance<IAppThemeManager>(appThemeManager);
  377. var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer);
  378. RegisterSingleInstance<IDlnaManager>(dlnaManager);
  379. var connectionManager = new ConnectionManager(dlnaManager, ServerConfigurationManager, LogManager.GetLogger("UpnpConnectionManager"), HttpClient);
  380. RegisterSingleInstance<IConnectionManager>(connectionManager);
  381. CollectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager"));
  382. RegisterSingleInstance(CollectionManager);
  383. var playlistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager);
  384. RegisterSingleInstance<IPlaylistManager>(playlistManager);
  385. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, FileSystemManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer);
  386. RegisterSingleInstance(LiveTvManager);
  387. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, FileSystemManager, UserManager, ChannelManager, LiveTvManager, ApplicationPaths, playlistManager);
  388. RegisterSingleInstance(UserViewManager);
  389. var contentDirectory = new ContentDirectory(dlnaManager, UserDataManager, ImageProcessor, LibraryManager, ServerConfigurationManager, UserManager, LogManager.GetLogger("UpnpContentDirectory"), HttpClient, LocalizationManager);
  390. RegisterSingleInstance<IContentDirectory>(contentDirectory);
  391. NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager);
  392. RegisterSingleInstance(NotificationManager);
  393. SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, ItemRepository);
  394. RegisterSingleInstance(SubtitleManager);
  395. ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
  396. RegisterSingleInstance(ChapterManager);
  397. EncodingManager = new EncodingManager(FileSystemManager, Logger,
  398. MediaEncoder, ChapterManager);
  399. RegisterSingleInstance(EncodingManager);
  400. var activityLogRepo = await GetActivityLogRepository().ConfigureAwait(false);
  401. RegisterSingleInstance(activityLogRepo);
  402. RegisterSingleInstance<IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager));
  403. var authContext = new AuthorizationContext();
  404. RegisterSingleInstance<IAuthorizationContext>(authContext);
  405. RegisterSingleInstance<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  406. RegisterSingleInstance<IAuthService>(new AuthService(UserManager, SessionManager, authContext, ServerConfigurationManager, ConnectManager));
  407. RegisterSingleInstance<ISubtitleEncoder>(new SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer));
  408. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  409. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  410. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  411. await ConfigureNotificationsRepository().ConfigureAwait(false);
  412. progress.Report(92);
  413. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);
  414. progress.Report(100);
  415. SetStaticProperties();
  416. await ((UserManager)UserManager).Initialize().ConfigureAwait(false);
  417. SetKernelProperties();
  418. }
  419. protected override INetworkManager CreateNetworkManager(ILogger logger)
  420. {
  421. return NativeApp.CreateNetworkManager(logger);
  422. }
  423. /// <summary>
  424. /// Registers the media encoder.
  425. /// </summary>
  426. /// <returns>Task.</returns>
  427. private async Task RegisterMediaEncoder(IProgress<double> progress)
  428. {
  429. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager)
  430. .GetFFMpegInfo(NativeApp.Environment, _startupOptions, progress).ConfigureAwait(false);
  431. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), JsonSerializer, info.EncoderPath, info.ProbePath, info.Version);
  432. RegisterSingleInstance(MediaEncoder);
  433. }
  434. /// <summary>
  435. /// Sets the kernel properties.
  436. /// </summary>
  437. private void SetKernelProperties()
  438. {
  439. LocalizedStrings.StringFiles = GetExports<LocalizedStringData>();
  440. }
  441. /// <summary>
  442. /// Gets the user repository.
  443. /// </summary>
  444. /// <returns>Task{IUserRepository}.</returns>
  445. private async Task<IUserRepository> GetUserRepository()
  446. {
  447. var repo = new SqliteUserRepository(JsonSerializer, LogManager, ApplicationPaths);
  448. await repo.Initialize().ConfigureAwait(false);
  449. return repo;
  450. }
  451. /// <summary>
  452. /// Gets the file organization repository.
  453. /// </summary>
  454. /// <returns>Task{IUserRepository}.</returns>
  455. private async Task<IFileOrganizationRepository> GetFileOrganizationRepository()
  456. {
  457. var repo = new SqliteFileOrganizationRepository(LogManager, ServerConfigurationManager.ApplicationPaths);
  458. await repo.Initialize().ConfigureAwait(false);
  459. return repo;
  460. }
  461. private async Task<IAuthenticationRepository> GetAuthenticationRepository()
  462. {
  463. var repo = new AuthenticationRepository(LogManager.GetLogger("AuthenticationRepository"), ServerConfigurationManager.ApplicationPaths);
  464. await repo.Initialize().ConfigureAwait(false);
  465. return repo;
  466. }
  467. private async Task<IActivityRepository> GetActivityLogRepository()
  468. {
  469. var repo = new ActivityRepository(LogManager.GetLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths);
  470. await repo.Initialize().ConfigureAwait(false);
  471. return repo;
  472. }
  473. private async Task<ISyncRepository> GetSyncRepository()
  474. {
  475. var repo = new SyncRepository(LogManager.GetLogger("SyncRepository"), ServerConfigurationManager.ApplicationPaths);
  476. await repo.Initialize().ConfigureAwait(false);
  477. return repo;
  478. }
  479. /// <summary>
  480. /// Configures the repositories.
  481. /// </summary>
  482. /// <returns>Task.</returns>
  483. private async Task ConfigureNotificationsRepository()
  484. {
  485. var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths);
  486. await repo.Initialize().ConfigureAwait(false);
  487. NotificationsRepository = repo;
  488. RegisterSingleInstance(NotificationsRepository);
  489. }
  490. /// <summary>
  491. /// Configures the repositories.
  492. /// </summary>
  493. /// <returns>Task.</returns>
  494. private async Task ConfigureDisplayPreferencesRepositories()
  495. {
  496. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  497. }
  498. /// <summary>
  499. /// Configures the item repositories.
  500. /// </summary>
  501. /// <returns>Task.</returns>
  502. private async Task ConfigureItemRepositories()
  503. {
  504. await ItemRepository.Initialize().ConfigureAwait(false);
  505. await ProviderRepository.Initialize().ConfigureAwait(false);
  506. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  507. }
  508. /// <summary>
  509. /// Configures the user data repositories.
  510. /// </summary>
  511. /// <returns>Task.</returns>
  512. private async Task ConfigureUserDataRepositories()
  513. {
  514. var repo = new SqliteUserDataRepository(ApplicationPaths, LogManager);
  515. await repo.Initialize().ConfigureAwait(false);
  516. ((UserDataManager)UserDataManager).Repository = repo;
  517. }
  518. /// <summary>
  519. /// Dirty hacks
  520. /// </summary>
  521. private void SetStaticProperties()
  522. {
  523. // For now there's no real way to inject these properly
  524. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  525. BaseItem.ConfigurationManager = ServerConfigurationManager;
  526. BaseItem.LibraryManager = LibraryManager;
  527. BaseItem.ProviderManager = ProviderManager;
  528. BaseItem.LocalizationManager = LocalizationManager;
  529. BaseItem.ItemRepository = ItemRepository;
  530. User.XmlSerializer = XmlSerializer;
  531. User.UserManager = UserManager;
  532. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  533. Folder.UserManager = UserManager;
  534. BaseItem.FileSystem = FileSystemManager;
  535. BaseItem.UserDataManager = UserDataManager;
  536. BaseItem.ChannelManager = ChannelManager;
  537. BaseItem.LiveTvManager = LiveTvManager;
  538. Folder.UserViewManager = UserViewManager;
  539. UserView.TVSeriesManager = TVSeriesManager;
  540. BaseItem.CollectionManager = CollectionManager;
  541. }
  542. /// <summary>
  543. /// Finds the parts.
  544. /// </summary>
  545. protected override void FindParts()
  546. {
  547. if (IsFirstRun)
  548. {
  549. RegisterServerWithAdministratorAccess();
  550. }
  551. base.FindParts();
  552. HttpServer.Init(GetExports<IRestfulService>(false));
  553. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  554. StartServer(true);
  555. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  556. GetExports<IVirtualFolderCreator>(),
  557. GetExports<IItemResolver>(),
  558. GetExports<IIntroProvider>(),
  559. GetExports<IBaseItemComparer>(),
  560. GetExports<ILibraryPostScanTask>());
  561. ProviderManager.AddParts(GetExports<IImageProvider>(),
  562. GetExports<IMetadataService>(),
  563. GetExports<IItemIdentityProvider>(),
  564. GetExports<IItemIdentityConverter>(),
  565. GetExports<IMetadataProvider>(),
  566. GetExports<IMetadataSaver>(),
  567. GetExports<IImageSaver>(),
  568. GetExports<IExternalId>());
  569. SeriesOrderManager.AddParts(GetExports<ISeriesOrderProvider>());
  570. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  571. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  572. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  573. ChapterManager.AddParts(GetExports<IChapterProvider>());
  574. SessionManager.AddParts(GetExports<ISessionControllerFactory>());
  575. ChannelManager.AddParts(GetExports<IChannel>(), GetExports<IChannelFactory>());
  576. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  577. SyncManager.AddParts(GetExports<ISyncProvider>());
  578. }
  579. /// <summary>
  580. /// Starts the server.
  581. /// </summary>
  582. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  583. private void StartServer(bool retryOnFailure)
  584. {
  585. try
  586. {
  587. ServerManager.Start(HttpServerUrlPrefixes);
  588. }
  589. catch (Exception ex)
  590. {
  591. Logger.ErrorException("Error starting http server", ex);
  592. if (retryOnFailure)
  593. {
  594. RegisterServerWithAdministratorAccess();
  595. StartServer(false);
  596. }
  597. else
  598. {
  599. throw;
  600. }
  601. }
  602. }
  603. /// <summary>
  604. /// Called when [configuration updated].
  605. /// </summary>
  606. /// <param name="sender">The sender.</param>
  607. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  608. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  609. {
  610. base.OnConfigurationUpdated(sender, e);
  611. if (!HttpServer.UrlPrefixes.SequenceEqual(HttpServerUrlPrefixes, StringComparer.OrdinalIgnoreCase))
  612. {
  613. NotifyPendingRestart();
  614. }
  615. }
  616. /// <summary>
  617. /// Restarts this instance.
  618. /// </summary>
  619. public override async Task Restart()
  620. {
  621. if (!CanSelfRestart)
  622. {
  623. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  624. }
  625. try
  626. {
  627. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  628. }
  629. catch (Exception ex)
  630. {
  631. Logger.ErrorException("Error sending server restart notification", ex);
  632. }
  633. Logger.Debug("Calling NativeApp.Restart");
  634. NativeApp.Restart();
  635. }
  636. /// <summary>
  637. /// Gets or sets a value indicating whether this instance can self update.
  638. /// </summary>
  639. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  640. public override bool CanSelfUpdate
  641. {
  642. get
  643. {
  644. #if DEBUG
  645. return false;
  646. #endif
  647. #pragma warning disable 162
  648. return NativeApp.CanSelfUpdate;
  649. #pragma warning restore 162
  650. }
  651. }
  652. /// <summary>
  653. /// Gets the composable part assemblies.
  654. /// </summary>
  655. /// <returns>IEnumerable{Assembly}.</returns>
  656. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  657. {
  658. var list = GetPluginAssemblies()
  659. .ToList();
  660. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  661. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  662. // Include composable parts in the Api assembly
  663. list.Add(typeof(ApiEntryPoint).Assembly);
  664. // Include composable parts in the Dashboard assembly
  665. list.Add(typeof(DashboardService).Assembly);
  666. // Include composable parts in the Model assembly
  667. list.Add(typeof(SystemInfo).Assembly);
  668. // Include composable parts in the Common assembly
  669. list.Add(typeof(IApplicationHost).Assembly);
  670. // Include composable parts in the Controller assembly
  671. list.Add(typeof(IServerApplicationHost).Assembly);
  672. // Include composable parts in the Providers assembly
  673. list.Add(typeof(ProviderUtils).Assembly);
  674. // Common implementations
  675. list.Add(typeof(TaskManager).Assembly);
  676. // Server implementations
  677. list.Add(typeof(ServerApplicationPaths).Assembly);
  678. // MediaEncoding
  679. list.Add(typeof(MediaEncoder).Assembly);
  680. // Dlna
  681. list.Add(typeof(DlnaEntryPoint).Assembly);
  682. // Local metadata
  683. list.Add(typeof(AlbumXmlProvider).Assembly);
  684. // Xbmc
  685. list.Add(typeof(ArtistNfoProvider).Assembly);
  686. list.AddRange(NativeApp.GetAssembliesWithParts());
  687. // Include composable parts in the running assembly
  688. list.Add(GetType().Assembly);
  689. return list;
  690. }
  691. /// <summary>
  692. /// Gets the plugin assemblies.
  693. /// </summary>
  694. /// <returns>IEnumerable{Assembly}.</returns>
  695. private IEnumerable<Assembly> GetPluginAssemblies()
  696. {
  697. try
  698. {
  699. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  700. .Select(LoadAssembly)
  701. .Where(a => a != null)
  702. .ToList();
  703. }
  704. catch (DirectoryNotFoundException)
  705. {
  706. return new List<Assembly>();
  707. }
  708. }
  709. /// <summary>
  710. /// Gets the system status.
  711. /// </summary>
  712. /// <returns>SystemInfo.</returns>
  713. public virtual SystemInfo GetSystemInfo()
  714. {
  715. return new SystemInfo
  716. {
  717. HasPendingRestart = HasPendingRestart,
  718. Version = ApplicationVersion.ToString(),
  719. IsNetworkDeployed = CanSelfUpdate,
  720. WebSocketPortNumber = HttpServerPort,
  721. SupportsNativeWebSocket = true,
  722. FailedPluginAssemblies = FailedAssemblies.ToList(),
  723. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  724. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  725. Id = SystemId,
  726. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  727. LogPath = ApplicationPaths.LogDirectoryPath,
  728. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  729. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  730. CachePath = ApplicationPaths.CachePath,
  731. MacAddress = GetMacAddress(),
  732. HttpServerPortNumber = HttpServerPort,
  733. OperatingSystem = Environment.OSVersion.ToString(),
  734. CanSelfRestart = CanSelfRestart,
  735. CanSelfUpdate = CanSelfUpdate,
  736. WanAddress = ConnectManager.WanApiAddress,
  737. HasUpdateAvailable = HasUpdateAvailable,
  738. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  739. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  740. IsRunningAsService = IsRunningAsService,
  741. SupportsRunningAsService = SupportsRunningAsService,
  742. ServerName = FriendlyName,
  743. LocalAddress = GetLocalIpAddress()
  744. };
  745. }
  746. /// <summary>
  747. /// Gets the local ip address.
  748. /// </summary>
  749. /// <returns>System.String.</returns>
  750. private string GetLocalIpAddress()
  751. {
  752. // Return the first matched address, if found, or the first known local address
  753. var address = HttpServerIpAddresses.FirstOrDefault();
  754. if (!string.IsNullOrWhiteSpace(address))
  755. {
  756. address = string.Format("http://{0}:{1}",
  757. address,
  758. ServerConfigurationManager.Configuration.HttpServerPortNumber.ToString(CultureInfo.InvariantCulture));
  759. }
  760. return address;
  761. }
  762. public IEnumerable<string> HttpServerIpAddresses
  763. {
  764. get
  765. {
  766. var localAddresses = NetworkManager.GetLocalIpAddresses()
  767. .ToList();
  768. if (localAddresses.Count < 2)
  769. {
  770. return localAddresses;
  771. }
  772. var httpServerAddresses = HttpServer.LocalEndPoints
  773. .Select(i => i.Split(':').FirstOrDefault())
  774. .Where(i => !string.IsNullOrEmpty(i))
  775. .ToList();
  776. // Cross-check the local ip addresses with addresses that have been received on with the http server
  777. var matchedAddresses = httpServerAddresses
  778. .Where(i => localAddresses.Contains(i, StringComparer.OrdinalIgnoreCase))
  779. .ToList();
  780. if (matchedAddresses.Count == 0)
  781. {
  782. return localAddresses.Take(1);
  783. }
  784. return matchedAddresses;
  785. }
  786. }
  787. public string FriendlyName
  788. {
  789. get
  790. {
  791. return string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.ServerName)
  792. ? Environment.MachineName
  793. : ServerConfigurationManager.Configuration.ServerName;
  794. }
  795. }
  796. public int HttpServerPort
  797. {
  798. get { return ServerConfigurationManager.Configuration.HttpServerPortNumber; }
  799. }
  800. /// <summary>
  801. /// Gets the mac address.
  802. /// </summary>
  803. /// <returns>System.String.</returns>
  804. private string GetMacAddress()
  805. {
  806. try
  807. {
  808. return NetworkManager.GetMacAddress();
  809. }
  810. catch (Exception ex)
  811. {
  812. Logger.ErrorException("Error getting mac address", ex);
  813. return null;
  814. }
  815. }
  816. /// <summary>
  817. /// Shuts down.
  818. /// </summary>
  819. public override async Task Shutdown()
  820. {
  821. try
  822. {
  823. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  824. }
  825. catch (Exception ex)
  826. {
  827. Logger.ErrorException("Error sending server shutdown notification", ex);
  828. }
  829. NativeApp.Shutdown();
  830. }
  831. /// <summary>
  832. /// Registers the server with administrator access.
  833. /// </summary>
  834. private void RegisterServerWithAdministratorAccess()
  835. {
  836. Logger.Info("Requesting administrative access to authorize http server");
  837. try
  838. {
  839. NativeApp.AuthorizeServer(
  840. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  841. HttpServerUrlPrefixes.First(),
  842. UdpServerEntryPoint.PortNumber,
  843. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  844. }
  845. catch (Exception ex)
  846. {
  847. Logger.ErrorException("Error authorizing server", ex);
  848. }
  849. }
  850. public event EventHandler HasUpdateAvailableChanged;
  851. private bool _hasUpdateAvailable;
  852. public bool HasUpdateAvailable
  853. {
  854. get { return _hasUpdateAvailable; }
  855. set
  856. {
  857. var fireEvent = value && !_hasUpdateAvailable;
  858. _hasUpdateAvailable = value;
  859. if (fireEvent)
  860. {
  861. EventHelper.FireEventIfNotNull(HasUpdateAvailableChanged, this, EventArgs.Empty, Logger);
  862. }
  863. }
  864. }
  865. /// <summary>
  866. /// Checks for update.
  867. /// </summary>
  868. /// <param name="cancellationToken">The cancellation token.</param>
  869. /// <param name="progress">The progress.</param>
  870. /// <returns>Task{CheckForUpdateResult}.</returns>
  871. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  872. {
  873. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  874. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, _remotePackageName, null, ApplicationVersion, ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  875. var versionObject = version == null || string.IsNullOrWhiteSpace(version.versionStr) ? null : new Version(version.versionStr);
  876. var isUpdateAvailable = versionObject != null && versionObject > ApplicationVersion;
  877. var result = versionObject != null ?
  878. new CheckForUpdateResult { AvailableVersion = versionObject.ToString(), IsUpdateAvailable = isUpdateAvailable, Package = version } :
  879. new CheckForUpdateResult { AvailableVersion = ApplicationVersion.ToString(), IsUpdateAvailable = false };
  880. HasUpdateAvailable = result.IsUpdateAvailable;
  881. if (result.IsUpdateAvailable)
  882. {
  883. Logger.Info("New application version is available: {0}", result.AvailableVersion);
  884. }
  885. return result;
  886. }
  887. /// <summary>
  888. /// Updates the application.
  889. /// </summary>
  890. /// <param name="package">The package that contains the update</param>
  891. /// <param name="cancellationToken">The cancellation token.</param>
  892. /// <param name="progress">The progress.</param>
  893. /// <returns>Task.</returns>
  894. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  895. {
  896. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  897. HasUpdateAvailable = false;
  898. OnApplicationUpdated(package);
  899. }
  900. /// <summary>
  901. /// Configures the automatic run at startup.
  902. /// </summary>
  903. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  904. protected override void ConfigureAutoRunAtStartup(bool autorun)
  905. {
  906. if (SupportsAutoRunAtStartup)
  907. {
  908. NativeApp.ConfigureAutoRun(autorun);
  909. }
  910. }
  911. }
  912. }