ApplicationHost.cs 38 KB

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