ApplicationHost.cs 38 KB

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