ApplicationHost.cs 45 KB

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