ApplicationHost.cs 39 KB

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