ApplicationHost.cs 37 KB

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