ApplicationHost.cs 43 KB

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