ApplicationHost.cs 39 KB

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