ApplicationHost.cs 40 KB

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