ApplicationHost.cs 40 KB

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