ApplicationHost.cs 42 KB

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