2
0

ApplicationHost.cs 42 KB

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