ApplicationHost.cs 44 KB

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