ApplicationHost.cs 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. CachePath = ApplicationPaths.CachePath,
  736. MacAddress = GetMacAddress(),
  737. HttpServerPortNumber = HttpServerPort,
  738. OperatingSystem = Environment.OSVersion.ToString(),
  739. CanSelfRestart = CanSelfRestart,
  740. CanSelfUpdate = CanSelfUpdate,
  741. WanAddress = GetWanAddress(),
  742. HasUpdateAvailable = _hasUpdateAvailable,
  743. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  744. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  745. IsRunningAsService = IsRunningAsService,
  746. ServerName = string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.ServerName) ? Environment.MachineName : ServerConfigurationManager.Configuration.ServerName
  747. };
  748. }
  749. public int HttpServerPort
  750. {
  751. get { return ServerConfigurationManager.Configuration.HttpServerPortNumber; }
  752. }
  753. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  754. private string GetWanAddress()
  755. {
  756. var ip = ServerConfigurationManager.Configuration.WanDdns;
  757. if (string.IsNullOrWhiteSpace(ip))
  758. {
  759. ip = WanAddressEntryPoint.WanAddress;
  760. }
  761. if (!string.IsNullOrEmpty(ip))
  762. {
  763. if (!ip.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
  764. !ip.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  765. {
  766. ip = "http://" + ip;
  767. }
  768. return ip + ":" + ServerConfigurationManager.Configuration.HttpServerPortNumber.ToString(_usCulture);
  769. }
  770. return null;
  771. }
  772. /// <summary>
  773. /// Gets the mac address.
  774. /// </summary>
  775. /// <returns>System.String.</returns>
  776. private string GetMacAddress()
  777. {
  778. try
  779. {
  780. return NetworkManager.GetMacAddress();
  781. }
  782. catch (Exception ex)
  783. {
  784. Logger.ErrorException("Error getting mac address", ex);
  785. return null;
  786. }
  787. }
  788. /// <summary>
  789. /// Shuts down.
  790. /// </summary>
  791. public override async Task Shutdown()
  792. {
  793. try
  794. {
  795. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  796. }
  797. catch (Exception ex)
  798. {
  799. Logger.ErrorException("Error sending server shutdown notification", ex);
  800. }
  801. NativeApp.Shutdown();
  802. }
  803. /// <summary>
  804. /// Registers the server with administrator access.
  805. /// </summary>
  806. private void RegisterServerWithAdministratorAccess()
  807. {
  808. Logger.Info("Requesting administrative access to authorize http server");
  809. try
  810. {
  811. ServerAuthorization.AuthorizeServer(
  812. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  813. HttpServerUrlPrefixes.First(),
  814. ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber,
  815. UdpServerEntryPoint.PortNumber,
  816. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  817. }
  818. catch (Exception ex)
  819. {
  820. Logger.ErrorException("Error authorizing server", ex);
  821. }
  822. }
  823. private bool _hasUpdateAvailable;
  824. /// <summary>
  825. /// Checks for update.
  826. /// </summary>
  827. /// <param name="cancellationToken">The cancellation token.</param>
  828. /// <param name="progress">The progress.</param>
  829. /// <returns>Task{CheckForUpdateResult}.</returns>
  830. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  831. {
  832. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  833. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, null, ApplicationVersion,
  834. ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  835. _hasUpdateAvailable = version != null;
  836. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  837. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  838. }
  839. /// <summary>
  840. /// Updates the application.
  841. /// </summary>
  842. /// <param name="package">The package that contains the update</param>
  843. /// <param name="cancellationToken">The cancellation token.</param>
  844. /// <param name="progress">The progress.</param>
  845. /// <returns>Task.</returns>
  846. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  847. {
  848. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  849. _hasUpdateAvailable = false;
  850. OnApplicationUpdated(package.version);
  851. }
  852. /// <summary>
  853. /// Configures the automatic run at startup.
  854. /// </summary>
  855. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  856. protected override void ConfigureAutoRunAtStartup(bool autorun)
  857. {
  858. if (SupportsAutoRunAtStartup)
  859. {
  860. Autorun.Configure(autorun);
  861. }
  862. }
  863. }
  864. }