ApplicationHost.cs 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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. private 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. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  380. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  381. UserDataManager = new UserDataManager(LogManager);
  382. RegisterSingleInstance(UserDataManager);
  383. UserRepository = await GetUserRepository().ConfigureAwait(false);
  384. RegisterSingleInstance(UserRepository);
  385. DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
  386. RegisterSingleInstance(DisplayPreferencesRepository);
  387. ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
  388. RegisterSingleInstance(ItemRepository);
  389. ProviderRepository = new SqliteProviderInfoRepository(ApplicationPaths, LogManager);
  390. RegisterSingleInstance(ProviderRepository);
  391. FileOrganizationRepository = await GetFileOrganizationRepository().ConfigureAwait(false);
  392. RegisterSingleInstance(FileOrganizationRepository);
  393. UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository);
  394. RegisterSingleInstance(UserManager);
  395. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager);
  396. RegisterSingleInstance(LibraryManager);
  397. LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager);
  398. RegisterSingleInstance(LibraryMonitor);
  399. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager);
  400. RegisterSingleInstance(ProviderManager);
  401. SeriesOrderManager = new SeriesOrderManager();
  402. RegisterSingleInstance(SeriesOrderManager);
  403. RegisterSingleInstance<ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager));
  404. SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager, UserManager);
  405. RegisterSingleInstance(SessionManager);
  406. HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", "mediabrowser", "dashboard/index.html");
  407. RegisterSingleInstance(HttpServer, false);
  408. progress.Report(10);
  409. ServerManager = new ServerManager(this, JsonSerializer, LogManager.GetLogger("ServerManager"), ServerConfigurationManager);
  410. RegisterSingleInstance(ServerManager);
  411. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager);
  412. RegisterSingleInstance(LocalizationManager);
  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. var newsService = new Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer);
  422. RegisterSingleInstance<INewsService>(newsService);
  423. var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, LogManager.GetLogger("FileOrganizationService"), LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager);
  424. RegisterSingleInstance<IFileOrganizationService>(fileOrganizationService);
  425. progress.Report(15);
  426. EncodingManager = new EncodingManager(ServerConfigurationManager, FileSystemManager, Logger, ItemRepository,
  427. MediaEncoder);
  428. RegisterSingleInstance(EncodingManager);
  429. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, Logger, ServerConfigurationManager, FileSystemManager);
  430. RegisterSingleInstance(ChannelManager);
  431. var appThemeManager = new AppThemeManager(ApplicationPaths, FileSystemManager, JsonSerializer, Logger);
  432. RegisterSingleInstance<IAppThemeManager>(appThemeManager);
  433. var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("DLNA"), JsonSerializer);
  434. RegisterSingleInstance<IDlnaManager>(dlnaManager);
  435. var collectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor);
  436. RegisterSingleInstance<ICollectionManager>(collectionManager);
  437. LiveTvManager = new LiveTvManager(ServerConfigurationManager, FileSystemManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager);
  438. RegisterSingleInstance(LiveTvManager);
  439. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  440. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  441. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  442. await ConfigureNotificationsRepository().ConfigureAwait(false);
  443. progress.Report(92);
  444. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);
  445. progress.Report(100);
  446. SetStaticProperties();
  447. await ((UserManager)UserManager).Initialize().ConfigureAwait(false);
  448. SetKernelProperties();
  449. }
  450. protected override INetworkManager CreateNetworkManager()
  451. {
  452. return new NetworkManager();
  453. }
  454. protected override IFileSystem CreateFileSystemManager()
  455. {
  456. return FileSystemFactory.CreateFileSystemManager(LogManager);
  457. }
  458. /// <summary>
  459. /// Registers the media encoder.
  460. /// </summary>
  461. /// <returns>Task.</returns>
  462. private async Task RegisterMediaEncoder(IProgress<double> progress)
  463. {
  464. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager).GetFFMpegInfo(progress).ConfigureAwait(false);
  465. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ApplicationPaths, JsonSerializer, info.Path, info.ProbePath, info.Version, FileSystemManager);
  466. RegisterSingleInstance(MediaEncoder);
  467. }
  468. /// <summary>
  469. /// Sets the kernel properties.
  470. /// </summary>
  471. private void SetKernelProperties()
  472. {
  473. LocalizedStrings.StringFiles = GetExports<LocalizedStringData>();
  474. }
  475. /// <summary>
  476. /// Gets the user repository.
  477. /// </summary>
  478. /// <returns>Task{IUserRepository}.</returns>
  479. private async Task<IUserRepository> GetUserRepository()
  480. {
  481. var repo = new SqliteUserRepository(JsonSerializer, LogManager, ApplicationPaths);
  482. await repo.Initialize().ConfigureAwait(false);
  483. return repo;
  484. }
  485. /// <summary>
  486. /// Gets the file organization repository.
  487. /// </summary>
  488. /// <returns>Task{IUserRepository}.</returns>
  489. private async Task<IFileOrganizationRepository> GetFileOrganizationRepository()
  490. {
  491. var repo = new SqliteFileOrganizationRepository(LogManager, ServerConfigurationManager.ApplicationPaths);
  492. await repo.Initialize().ConfigureAwait(false);
  493. return repo;
  494. }
  495. /// <summary>
  496. /// Configures the repositories.
  497. /// </summary>
  498. /// <returns>Task.</returns>
  499. private async Task ConfigureNotificationsRepository()
  500. {
  501. var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths);
  502. await repo.Initialize().ConfigureAwait(false);
  503. NotificationsRepository = repo;
  504. RegisterSingleInstance(NotificationsRepository);
  505. }
  506. /// <summary>
  507. /// Configures the repositories.
  508. /// </summary>
  509. /// <returns>Task.</returns>
  510. private async Task ConfigureDisplayPreferencesRepositories()
  511. {
  512. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  513. }
  514. /// <summary>
  515. /// Configures the item repositories.
  516. /// </summary>
  517. /// <returns>Task.</returns>
  518. private async Task ConfigureItemRepositories()
  519. {
  520. await ItemRepository.Initialize().ConfigureAwait(false);
  521. await ProviderRepository.Initialize().ConfigureAwait(false);
  522. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  523. }
  524. /// <summary>
  525. /// Configures the user data repositories.
  526. /// </summary>
  527. /// <returns>Task.</returns>
  528. private async Task ConfigureUserDataRepositories()
  529. {
  530. var repo = new SqliteUserDataRepository(ApplicationPaths, LogManager);
  531. await repo.Initialize().ConfigureAwait(false);
  532. ((UserDataManager)UserDataManager).Repository = repo;
  533. }
  534. /// <summary>
  535. /// Dirty hacks
  536. /// </summary>
  537. private void SetStaticProperties()
  538. {
  539. // For now there's no real way to inject these properly
  540. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  541. BaseItem.ConfigurationManager = ServerConfigurationManager;
  542. BaseItem.LibraryManager = LibraryManager;
  543. BaseItem.ProviderManager = ProviderManager;
  544. BaseItem.LocalizationManager = LocalizationManager;
  545. BaseItem.ItemRepository = ItemRepository;
  546. User.XmlSerializer = XmlSerializer;
  547. User.UserManager = UserManager;
  548. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  549. Folder.UserManager = UserManager;
  550. BaseItem.FileSystem = FileSystemManager;
  551. BaseItem.UserDataManager = UserDataManager;
  552. }
  553. /// <summary>
  554. /// Finds the parts.
  555. /// </summary>
  556. protected override void FindParts()
  557. {
  558. if (IsFirstRun)
  559. {
  560. RegisterServerWithAdministratorAccess();
  561. }
  562. base.FindParts();
  563. HttpServer.Init(GetExports<IRestfulService>(false));
  564. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  565. StartServer(true);
  566. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  567. GetExports<IVirtualFolderCreator>(),
  568. GetExports<IItemResolver>(),
  569. GetExports<IIntroProvider>(),
  570. GetExports<IBaseItemComparer>(),
  571. GetExports<ILibraryPostScanTask>());
  572. ProviderManager.AddParts(GetExports<IImageProvider>(), GetExports<IMetadataService>(), GetExports<IMetadataProvider>(),
  573. GetExports<IMetadataSaver>(),
  574. GetExports<IImageSaver>(),
  575. GetExports<IExternalId>());
  576. SeriesOrderManager.AddParts(GetExports<ISeriesOrderProvider>());
  577. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  578. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  579. SessionManager.AddParts(GetExports<ISessionControllerFactory>());
  580. ChannelManager.AddParts(GetExports<IChannel>());
  581. }
  582. /// <summary>
  583. /// Starts the server.
  584. /// </summary>
  585. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  586. private void StartServer(bool retryOnFailure)
  587. {
  588. try
  589. {
  590. ServerManager.Start(HttpServerUrlPrefixes, ServerConfigurationManager.Configuration.EnableHttpLevelLogging);
  591. }
  592. catch (Exception ex)
  593. {
  594. Logger.ErrorException("Error starting http server", ex);
  595. if (retryOnFailure)
  596. {
  597. RegisterServerWithAdministratorAccess();
  598. StartServer(false);
  599. }
  600. else
  601. {
  602. throw;
  603. }
  604. }
  605. ServerManager.StartWebSocketServer();
  606. }
  607. /// <summary>
  608. /// Called when [configuration updated].
  609. /// </summary>
  610. /// <param name="sender">The sender.</param>
  611. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  612. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  613. {
  614. base.OnConfigurationUpdated(sender, e);
  615. HttpServer.EnableHttpRequestLogging = ServerConfigurationManager.Configuration.EnableHttpLevelLogging;
  616. if (!HttpServer.UrlPrefixes.SequenceEqual(HttpServerUrlPrefixes, StringComparer.OrdinalIgnoreCase))
  617. {
  618. NotifyPendingRestart();
  619. }
  620. else if (!ServerManager.SupportsNativeWebSocket && ServerManager.WebSocketPortNumber != ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber)
  621. {
  622. NotifyPendingRestart();
  623. }
  624. }
  625. /// <summary>
  626. /// Restarts this instance.
  627. /// </summary>
  628. public override async Task Restart()
  629. {
  630. if (!CanSelfRestart)
  631. {
  632. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  633. }
  634. try
  635. {
  636. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  637. }
  638. catch (Exception ex)
  639. {
  640. Logger.ErrorException("Error sending server restart notification", ex);
  641. }
  642. NativeApp.Restart();
  643. }
  644. /// <summary>
  645. /// Gets or sets a value indicating whether this instance can self update.
  646. /// </summary>
  647. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  648. public override bool CanSelfUpdate
  649. {
  650. get
  651. {
  652. #if DEBUG
  653. return false;
  654. #endif
  655. #pragma warning disable 162
  656. return NativeApp.CanSelfUpdate;
  657. #pragma warning restore 162
  658. }
  659. }
  660. /// <summary>
  661. /// Gets the composable part assemblies.
  662. /// </summary>
  663. /// <returns>IEnumerable{Assembly}.</returns>
  664. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  665. {
  666. var list = GetPluginAssemblies()
  667. .ToList();
  668. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  669. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  670. // Include composable parts in the Api assembly
  671. list.Add(typeof(ApiEntryPoint).Assembly);
  672. // Include composable parts in the Dashboard assembly
  673. list.Add(typeof(DashboardService).Assembly);
  674. // Include composable parts in the Model assembly
  675. list.Add(typeof(SystemInfo).Assembly);
  676. // Include composable parts in the Common assembly
  677. list.Add(typeof(IApplicationHost).Assembly);
  678. // Include composable parts in the Controller assembly
  679. list.Add(typeof(IServerApplicationHost).Assembly);
  680. // Include composable parts in the Providers assembly
  681. list.Add(typeof(ProviderUtils).Assembly);
  682. // Common implementations
  683. list.Add(typeof(TaskManager).Assembly);
  684. // Server implementations
  685. list.Add(typeof(ServerApplicationPaths).Assembly);
  686. // MediaEncoding
  687. list.Add(typeof(MediaEncoder).Assembly);
  688. // Dlna
  689. list.Add(typeof(PlayToServerEntryPoint).Assembly);
  690. list.AddRange(Assemblies.GetAssembliesWithParts());
  691. // Include composable parts in the running assembly
  692. list.Add(GetType().Assembly);
  693. return list;
  694. }
  695. /// <summary>
  696. /// Gets the plugin assemblies.
  697. /// </summary>
  698. /// <returns>IEnumerable{Assembly}.</returns>
  699. private IEnumerable<Assembly> GetPluginAssemblies()
  700. {
  701. try
  702. {
  703. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  704. .Select(LoadAssembly)
  705. .Where(a => a != null)
  706. .ToList();
  707. }
  708. catch (DirectoryNotFoundException)
  709. {
  710. return new List<Assembly>();
  711. }
  712. }
  713. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  714. /// <summary>
  715. /// Gets the system status.
  716. /// </summary>
  717. /// <returns>SystemInfo.</returns>
  718. public virtual SystemInfo GetSystemInfo()
  719. {
  720. return new SystemInfo
  721. {
  722. HasPendingRestart = HasPendingRestart,
  723. Version = ApplicationVersion.ToString(),
  724. IsNetworkDeployed = CanSelfUpdate,
  725. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  726. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  727. FailedPluginAssemblies = FailedAssemblies.ToList(),
  728. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  729. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  730. Id = _systemId,
  731. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  732. LogPath = ApplicationPaths.LogDirectoryPath,
  733. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  734. CachePath = ApplicationPaths.CachePath,
  735. MacAddress = GetMacAddress(),
  736. HttpServerPortNumber = HttpServerPort,
  737. OperatingSystem = Environment.OSVersion.ToString(),
  738. CanSelfRestart = CanSelfRestart,
  739. CanSelfUpdate = CanSelfUpdate,
  740. WanAddress = GetWanAddress(),
  741. HasUpdateAvailable = _hasUpdateAvailable,
  742. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  743. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  744. IsRunningAsService = IsRunningAsService,
  745. ServerName = string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.ServerName) ? Environment.MachineName : ServerConfigurationManager.Configuration.ServerName
  746. };
  747. }
  748. public int HttpServerPort
  749. {
  750. get { return ServerConfigurationManager.Configuration.HttpServerPortNumber; }
  751. }
  752. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  753. private string GetWanAddress()
  754. {
  755. var ip = ServerConfigurationManager.Configuration.WanDdns;
  756. if (string.IsNullOrWhiteSpace(ip))
  757. {
  758. ip = WanAddressEntryPoint.WanAddress;
  759. }
  760. if (!string.IsNullOrEmpty(ip))
  761. {
  762. if (!ip.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
  763. !ip.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  764. {
  765. ip = "http://" + ip;
  766. }
  767. return ip + ":" + ServerConfigurationManager.Configuration.HttpServerPortNumber.ToString(_usCulture);
  768. }
  769. return null;
  770. }
  771. /// <summary>
  772. /// Gets the mac address.
  773. /// </summary>
  774. /// <returns>System.String.</returns>
  775. private string GetMacAddress()
  776. {
  777. try
  778. {
  779. return NetworkManager.GetMacAddress();
  780. }
  781. catch (Exception ex)
  782. {
  783. Logger.ErrorException("Error getting mac address", ex);
  784. return null;
  785. }
  786. }
  787. /// <summary>
  788. /// Shuts down.
  789. /// </summary>
  790. public override async Task Shutdown()
  791. {
  792. try
  793. {
  794. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  795. }
  796. catch (Exception ex)
  797. {
  798. Logger.ErrorException("Error sending server shutdown notification", ex);
  799. }
  800. NativeApp.Shutdown();
  801. }
  802. /// <summary>
  803. /// Registers the server with administrator access.
  804. /// </summary>
  805. private void RegisterServerWithAdministratorAccess()
  806. {
  807. Logger.Info("Requesting administrative access to authorize http server");
  808. try
  809. {
  810. ServerAuthorization.AuthorizeServer(
  811. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  812. HttpServerUrlPrefixes.First(),
  813. ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber,
  814. UdpServerEntryPoint.PortNumber,
  815. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  816. }
  817. catch (Exception ex)
  818. {
  819. Logger.ErrorException("Error authorizing server", ex);
  820. }
  821. }
  822. private bool _hasUpdateAvailable;
  823. /// <summary>
  824. /// Checks for update.
  825. /// </summary>
  826. /// <param name="cancellationToken">The cancellation token.</param>
  827. /// <param name="progress">The progress.</param>
  828. /// <returns>Task{CheckForUpdateResult}.</returns>
  829. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  830. {
  831. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  832. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, null, ApplicationVersion,
  833. ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  834. _hasUpdateAvailable = version != null;
  835. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  836. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  837. }
  838. /// <summary>
  839. /// Updates the application.
  840. /// </summary>
  841. /// <param name="package">The package that contains the update</param>
  842. /// <param name="cancellationToken">The cancellation token.</param>
  843. /// <param name="progress">The progress.</param>
  844. /// <returns>Task.</returns>
  845. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  846. {
  847. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  848. _hasUpdateAvailable = false;
  849. OnApplicationUpdated(package.version);
  850. }
  851. /// <summary>
  852. /// Configures the automatic run at startup.
  853. /// </summary>
  854. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  855. protected override void ConfigureAutoRunAtStartup(bool autorun)
  856. {
  857. if (SupportsAutoRunAtStartup)
  858. {
  859. Autorun.Configure(autorun);
  860. }
  861. }
  862. }
  863. }