2
0

ApplicationHost.cs 38 KB

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